简体   繁体   English

按类名获取并添加类

[英]Get by class name and add class

The first one, I can use document.getElementById to get the object, but on some websites, like the second, there is no id in element, but I also want to get the object with class name and add other class.第一个,我可以使用 document.getElementById 来获取对象,但在某些网站上,如第二个,元素中没有 id,但我也想获取带有类名的对象并添加其他类。 How can I do this ?我怎样才能做到这一点 ? And do not use JQuery, Need If one class exist add other class to other element并且不要使用 JQuery,如果存在一个类,需要将另一个类添加到其他元素

  if (document.getElementsByClassName('class7') !== null) {
  document.querySelectorAll('class2 class4').className += " classtobeadded";
}

Assuming you want to select all elements that have class 'class1', and add class 'class2' to them, this will do it:假设您要选择具有类“class1”的所有元素,并将类“class2”添加到它们,这将执行以下操作:

document.querySelectorAll('.class1').forEach(item => {
    item.classList.add('class2');
});

Note that when using querySelector() or querySelectorAll() , you should use CSS selectors like '.'请注意,在使用querySelector()querySelectorAll() ,您应该使用像 '.' 这样的 CSS 选择器。 before a class and '#' before an ID.在类之前和 ID 之前的“#”。

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

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