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

167
Visualizações
Javascript: getelementsbyid inside of class that is changing (active)

This is my HTML code:

<div class="foo active">
    <div id="bar">
        Hello world!
    </div>
</div>
Hello world!

The div class active is always changing so i first need to get into the class foo active

How can I get to change "Hello world!"?

var targetDiv = document.getElementByClassName("foo active")[0].getElementsById("bar");

is not working.

I know when the code is like this:

<div id="foo">
    <div class="bar">
        Hello world!
    </div>
</div>

I just need to:

var targetDiv = document.getElementById("foo").getElementsByClassName("bar")[0];
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You just need to target the ID of "bar".

document.getElementById("bar").innerHTML = "new text";

about 4 years ago · Juan Pablo Isaza Relatório

0

If you want to access an element with an id in HTML, you do not have to use:

var targetDiv = document.getElementByClassName("foo")[0].getElementsById("bar");

You can simply do this:

var targetDiv = document.getElementsById("bar");

Also, You need something to run the code. Example if you click a button the text changes or if you want the text to change as soon as the DOM content loads you can add the DOMContentLoaded event listener.

Try this code:

<div class="foo">
<div id="bar">
    Hello world!
</div>
<button onClick = "changeText()">Change Text!</button>
changeText = () => {
 const targetVar = document.getElementById("bar");
 targetVar.innerHTML = "Something else!";
}
about 4 years ago · Juan Pablo Isaza Relatório

0

To provide some context as to why this is happening, getElementById and getElementsByClassName return an Element and an array of Elements respectively. The Element object has a series of functions available to call, including (but not limited to) getElementsByClassName. However, the getElementById function is not available on Elements, only on the Document object itself, meaning that you can't call it in the way you were attempting to in your first example.

To circumvent this, you can either find the element by ID straight away and work from there

var targetDiv = document.getElementById("foo")

or you can use querySelector and querySelectorAll

const targetDiv = document.querySelector(".foo.active #bar")

// The result you want
const targetDiv = document.querySelector(".foo.active #bar")
console.log(targetDiv)

// An example of a result not filtered by the active class
const exampleDiv = document.querySelectorAll(".foo #bar")
console.log(exampleDiv)
<div class="foo active">
    <div id="bar">
        Hello world!
    </div>
</div>

<div class="foo inactive">
    <div id="bar">
        Hello world!
    </div>
</div>

Note that ideally there is only one element with a given ID on a page as IDs are intended to be unique. With that being said, my example isn't best practice, but it sounds like in your example there may be multiple elements with the same ID.

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