简体   繁体   English

使用 javascript 将 class 添加到元素的第一个子元素

[英]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 string, enclose the string in string delimiters, like '要使用字符串,请将字符串括在字符串分隔符中,例如'
  • 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只接受标签名称(如pspan - 它根本不灵活):

     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.

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