【问题标题】:How to add a class in javascript with selector chaining?如何使用选择器链接在 javascript 中添加一个类?
【发布时间】:2016-07-31 01:24:15
【问题描述】:

我需要为大量 标签添加一个类。我必须使用 querySelectorAll 方法选择 a 标签,并且选择所有元素。但是当我尝试向他们添加一个类时,它不会添加。

我已经尝试了以下示例。

var qc=document.querySelectorAll(".Label ul li a");
qc.className+="newcls";

https://jsfiddle.net/ahhvovvv/

但是我可以通过jQuery添加它,但不要使用jQuery。
工作的 jQuery 代码是

$(document).ready(function(){

   $(".Label ul li a").addClass("newcls");

});

【问题讨论】:

  • qc 是一个集合。您需要对其进行迭代并将类名添加到每个集合元素。 jQuery 会自动为您完成。
  • 另外,qc[i].classList.add("newcls") 可能更适合您。见:MDN classList
  • [].forEach.call(qc, el => el.classList.add('newCls'));

标签: javascript


【解决方案1】:

在您的代码中,qc 是集合。你应该遍历它。 并且 className 不是一个集合,它是一个字符串,其中类名用空格分隔。所以这是你的代码修复

var qc=document.querySelectorAll(".Label ul li a");
for(var i=0; i<qc.length; i++) {
    qc.classList.add("newcls");
    //replace with next line if you need this working in IE before version 10 
    //qc.item(i).className+=" newcls";
}

【讨论】:

【解决方案2】:

我建议:

// converts the collection of elements returned from
// document.querySelectorAll() into an Array, using
// Array.from(), then iterates over that Array using
// Array.prototype.forEach():
Array.from( document.querySelectorAll(".Label ul li a") ).forEach(

  // using arrow function syntax to perform the same
  // action on each <a> ('aElement') within the
  // array; here using Element.classList API to
  // add the given class-name:
  aElement => aElement.classList.add('newClass')
);

【讨论】:

【解决方案3】:

您必须遍历集合,一种方法可能是:

var qc = document.querySelectorAll(".Label ul li a");
[].forEach.call(qc, function(item) {
    item.className+=" newcls";
})

Fiddle updated

如果您要使用className,请记住在课程前添加一个空格,因为您正在编辑整个class,否则您可以使用

item.classList.add('newcls');

【讨论】:

  • 我认为使用 [].forEach.call 比使用 Array.from 更安全的解决方案。
  • 这是一个简单的解决方案,但是有一些 highlighted problems 来自 Todd Motto,在大型代码库中工作时要牢记这一点很有趣。但是我认为使用classList 而不是className 也是一个好习惯。
猜你喜欢
  • 2023-04-08
  • 1970-01-01
  • 2018-02-19
  • 2014-03-15
  • 2022-11-07
  • 1970-01-01
  • 1970-01-01
  • 2011-07-29
  • 2014-03-01
相关资源
最近更新 更多