如何通过父元素ID更改子元素的类样式? [英] How to change class style for children element by parent element id?
问题描述
例如,我有简单的html代码:
< a id ="news" href =#">< div class ="> News</div></a>
如何在纯JavaScript上通过href的ID更改div元素的类样式?还是更好地在类中为"a"元素描述div属性?(怎么办?)
您可以使用 ...因为div是新闻"元素的第一个子元素.或者,如果您要添加"foo"类: 同样值得一看的是 如果您可能还有其他元素,空格/文本节点等,则可以查看 更多探索: For example I have simple html code: 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 ?) You can get a reference to your "news" element using For instance, this would work with the HTML you've quoted to set the "foo" class on the element: ...because the div is the first child of the "news" element. Or if you want to add the "foo" class: Also worth looking at If you might have other elements, whitespace/text nodes, etc., you might look at More to explore: 这篇关于如何通过父元素ID更改子元素的类样式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! childNodes
并设置div的
document.getElementById("news").childNodes [0] .className ="foo";
document.getElementById("news").childNodes [0] .className + ="foo";
querySelector
和 querySelectorAll
,受支持大多数(但不是全部)浏览器(更多支持).> <a id="news" href="#"><div class="" >News</div></a>
getElementById
. Then you can find the div
in its childNodes
and set the div's className
property.document.getElementById("news").childNodes[0].className = "foo";
document.getElementById("news").childNodes[0].className += " foo";
querySelector
and querySelectorAll
, which are supported by most (but not all) browsers currently in use (more on support).getElementsByTagName
rather than childNodes
so you only get the specific elements you're interested in:document.getElementById("news").getElementsByTagName('div')[0].className += " foo";