Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
933 views
in Technique[技术] by (71.8m points)

javascript - How to change class style for children element by parent element id?

For example I have simple html code:

 <a id="news" href="#"><div class="" >News</div></a>

How to change class style for div element by id of href on pure javascript ? Or may be better describe div properties in class for "a" element ? ( How to do it ?)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...