Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

143
Views
¿Por qué no puedo acceder a los objetos svg usando el objeto html?

Ejemplo en Internet, pueden llamar objetos en archivos svg fácilmente. Pero no puedo alcanzarlos. Aquí está mi código html``

 <html lang="en"> <head> <title>SVG Example</title> <script src="mysvg.js"></script> </head> <body> <div> <button style="width: 100px; height: 50px" onclick="changeColor()">Change Color</button> <object data="test.svg" type="image/svg+xml"></object> </div> </body> </html>

Este es mi código de archivo .js:

 function changeColor() { const svg = document.getElementById("layer1"); const motor1 = document.getElementById("g320"); const ellipse = document.getElementById("ellipse205"); ellipse.setAttribute("style","fill:green;stroke:green;stroke-width:2"); motor1.appendChild(svg); ellipse.appendChild(motor1); }

¿Qué hago mal, por qué esto no funciona? No entiendo.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

El contenido de un <object> SVG es parte de un DOM diferente al del documento anfitrión. Acceder es un proceso de dos pasos:

  • espera a que cargue el contenido
  • acceda a su DOM con HTMLObjectElement.contentDocument

Como esto:

 document.querySelector('object[data="test.svg"]').addEventListener("load", function () { document.querySelector('button').addEventListener("click", changeColor); } function changeColor() { const innerDocument = this.contentDocument; const svg = innerDocument.getElementById("layer1"); const motor1 = innerDocument.getElementById("g320"); const ellipse = innerDocument.getElementById("ellipse205"); ellipse.setAttribute("style","fill:green;stroke:green;stroke-width:2"); motor1.appendChild(svg); ellipse.appendChild(motor1); }

Tenga en cuenta que este tipo de acceso está sujeto a la Política del mismo origen . Significa que el archivo HTML del host y el SVG deben servirse desde el mismo dominio, o desde localhost , o un encabezado CORS debe permitirlo explícitamente. Si los carga con el protocolo file:// , this.contentDocument también devolverá null .

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!