Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

144
Visualizações
Why I cannot reach the svg objects using from html object?

Example on the Internet, they can call objects in svg files easily. But i cannot reach them. Here is my html code``

<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>

This is my .js file code:

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);
}

What i do wrong, why this is not working? I do not understand.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The content of a SVG <object> is part of a different DOM than the host document. Accessing it is a two-step process:

  • wait for the content to load
  • access its DOM with HTMLObjectElement.contentDocument

Like this:

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);
}

Note that this sort of access is subject to the Same-origin Policy. It means that the host HTML file and the SVG either need to be served from the same domain, or from localhost, or a CORS header must explicitely allow it. If you load them with the file:// protocol, this.contentDocument will also return null.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda