如何通过父元素ID更改子元素的类样式? [英] How to change class style for children element by parent element id?

查看:90
本文介绍了如何通过父元素ID更改子元素的类样式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我有简单的html代码:

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

如何在纯JavaScript上通过href的ID更改div元素的类样式?还是更好地在类中为"a"元素描述div属性?(怎么办?)

解决方案

您可以使用 childNodes 并设置div的

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

...因为div是新闻"元素的第一个子元素.或者,如果您要添加"foo"类:

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

同样值得一看的是 querySelector querySelectorAll ,受支持大多数(但不是全部)浏览器(更多支持).

如果您可能还有其他元素,空格/文本节点等,则可以查看

更多探索:

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 ?)

解决方案

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:

这篇关于如何通过父元素ID更改子元素的类样式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆