简体   繁体   English

如何通过父元素id更改子元素的类样式?

[英]How to change class style for children element by parent element id?

For example I have simple html code: 例如,我有简单的HTML代码:

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

How to change class style for div element by id of href on pure javascript ? 如何在纯javascript上用href的id更改div元素的类样式? Or may be better describe div properties in class for "a" element ? 或者可能更好地在类中为“a”元素描述div属性? ( How to do it ?) ( 怎么做 ?)

You can get a reference to your "news" element using getElementById . 您可以使用getElementById获取对“news”元素的引用。 Then you can find the div in its childNodes and set the div's className property. 然后你可以在它的childNodes找到div并设置div的className属性。

For instance, this would work with the HTML you've quoted to set the "foo" class on the element: 例如,这将与您引用的HTML一起使用,以在元素上设置“foo”类:

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

...because the div is the first child of the "news" element. ...因为div是“新闻”元素的第一个孩子。 Or if you want to add the "foo" class: 或者如果你想添加 “foo”类:

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 ). 另外值得查看querySelectorquerySelectorAll ,它们目前正在使用的大多数 (但不是全部)浏览器都支持( 更多支持 )。

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: 如果您可能有其他元素,空格/文本节点等,您可能会查看getElementsByTagName而不是childNodes因此您只能获得您感兴趣的特定元素:

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

More to explore: 更多探索:

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 当然,如果您的浏览器不支持querySelector您将不得不像这样做更多的finagling

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

As in HTML5, it is better to use dataset modifiers, like this: 与在HTML5中一样,最好使用数据集修饰符,如下所示:

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

and then in javascript: 然后在javascript中:

someElement.dataset.alt = "white"
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');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM