[英]add a class to an element's first child with javascript
New to js and trying to add a class to every section's first child automatically. js 新手并尝试自动将 class 添加到每个部分的第一个子项。 I'm thinking something like:
我在想类似的事情:
<script>
var element=document.getElementsByTagName(section p:first-child);
element.classList.add('firstp');
</script>
but it's not producing any effect in the document.但它不会在文档中产生任何影响。 Any help?
有什么帮助吗?
getElementsByTagName
returns a collection, not an element, so you'd have to iterate over it getElementsByTagName
返回一个集合,而不是一个元素,因此您必须对其进行迭代'
'
To use a selector string to select elements, use querySelectorAll
.要将选择器字符串用于 select 元素,请使用
querySelectorAll
。 getElementsByTagName
only accepts tag names (like p
, or span
- it's not flexible at all): getElementsByTagName
只接受标签名称(如p
或span
- 它根本不灵活):
var allFirstPs = document.querySelectorAll('section p:first-child'); allFirstPs.forEach((p) => { p.classList.add('firstp'); });
To support older browsers (since NodeList.prototype.forEach
is a somewhat new method), use Array.prototype.forEach
instead:要支持旧浏览器(因为
NodeList.prototype.forEach
是一种新方法),请改用Array.prototype.forEach
:
var allFirstPs = document.querySelectorAll('section p:first-child');
Array.prototype.forEach.call(
allFirstPs,
function(p) {
p.classList.add('firstp');
}
);
You could use querySelectorAll
(to get the paragraphs) and forEach
(to iterate over each paragraph) to accomplish this:您可以使用
querySelectorAll
(获取段落)和forEach
(遍历每个段落)来完成此操作:
var elements = document.querySelectorAll('section p:first-child'); elements.forEach((e) => { e.classList.add('firstp'); });
.firstp { color: red; }
<section> <p>1st</p> <p>2nd</p> <p>3rd</p> </section> <section> <p>1st</p> <p>2nd</p> <p>3rd</p> </section> <section> <p>1st</p> <p>2nd</p> <p>3rd</p> </section>
use querySelectorAll:使用 querySelectorAll:
var elements = document.querySelectorAll('section p:first-child');
and iterate over result:并迭代结果:
[...elements].forEach((element) => element.classList.add('firstp'));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.