Home > OS >  Javascript: getelementsbyid inside of class that is changing (active)
Javascript: getelementsbyid inside of class that is changing (active)

Time:12-29

This is my HTML code:

<div >
    <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 >
        Hello world!
    </div>
</div>

I just need to:

var targetDiv = document.getElementById("foo").getElementsByClassName("bar")[0];

CodePudding user response:

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

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

CodePudding user response:

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 >
<div id="bar">
    Hello world!
</div>
<button onClick = "changeText()">Change Text!</button>
changeText = () => {
 const targetVar = document.getElementById("bar");
 targetVar.innerHTML = "Something else!";
}

CodePudding user response:

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 >
    <div id="bar">
        Hello world!
    </div>
</div>

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

  • Related