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:
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…