Skip to content Skip to sidebar Skip to footer

How To Change Class Style For Children Element By Parent Element Id?

For example I have simple html code:
News
How to change class style for div element by id of href on pure j

Solution 1:

You can get a reference to your "news" element using getElementById. Then you can find the div in its childNodes and set the div's className property.

For instance, this would work with the HTML you've quoted to set the "foo" class on the element:

document.getElementById("news").childNodes[0].className = "foo";

...because the div is the first child of the "news" element. Or if you want to add the "foo" class:

document.getElementById("news").childNodes[0].className += " foo";

Also worth looking at querySelector and querySelectorAll, which are supported by most (but not all) browsers currently in use (more on support).

If you might have other elements, whitespace/text nodes, etc., you might look at getElementsByTagName rather than childNodes so you only get the specific elements you're interested in:

document.getElementById("news").getElementsByTagName('div')[0].className += " foo";

More to explore:

Solution 2:

There are a number of ways to do it but assuming the direct structure above.

var new_class = "ClassName";
document.querySelector('a#news > div').setAttribute('class', new_class);

Of course if your browser doesn't support querySelector you'll have to do a bit more finagling like this

document.getElementById('news').childNodes[0].setAttribute( 'class', new_class );

Solution 3:

var newsA = document.getElementById('news');
var myDiv = newsA.getElementsByTagName('div')[0];
myDiv.setAttribute('class', 'myClass');

That is one way.

To turn that into one nice line of code:

document.getElementById('news').getElementsByTagName('div')[0].setAttribute('class', 'myClass');

Solution 4:

As in HTML5, it is better to use dataset modifiers, like this:

.some-content[data-alt = "white"] {
    background: white;
}

and then in javascript:

someElement.dataset.alt = "white"

Post a Comment for "How To Change Class Style For Children Element By Parent Element Id?"