我想在访问特定网址时添加一个类。

huangapple go评论59阅读模式
英文:

I want to add a class when accessing a specific url

问题

I entered the code as below so that the class is added only in a specific URL, but it doesn't work.

Could you please help me what is wrong?

if (location.href.indexOf('url') > -1) {
    document.getElementsByClassName('className').classList.add('NewClass');
}
英文:

I entered the code as below so that the class is added only in a specific url, but it doesn't work.

Could you please help me what is wrong?

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

if(location.href.indexOf(&#39;url&#39;) &gt; -1){ 
    document.getElementsByClassName(&#39;className&#39;).classList.add(&#39;NewClass&#39;);
}

<!-- end snippet -->

答案1

得分: 1

getElementsByClassName方法返回一个包含所有具有指定类名的元素的HTML集合。要向集合中的元素添加类,您需要遍历集合并将类添加到每个单独的元素中。

尝试这样做:

if (location.href.indexOf('url') > -1) { 
  var elements = document.getElementsByClassName('className');
  for (var i = 0; i < elements.length; i++) {
    elements[i].classList.add('NewClass');
  }
}

在这段代码中,我们首先将HTML集合存储在elements变量中。然后,我们使用for循环遍历集合中的每个元素,并使用classList.add方法向每个单独的元素添加类'NewClass'。

英文:

The getElementsByClassName method returns an HTML collection which containing all the elements with the specified class name. To add a class to the elements in the collection, you need to loop through the collection and add the class to each individual element.

Try this:

if (location.href.indexOf(&#39;url&#39;) &gt; -1) { 
  var elements = document.getElementsByClassName(&#39;className&#39;);
  for (var i = 0; i &lt; elements.length; i++) {
    elements[i].classList.add(&#39;NewClass&#39;);
  }
}

In this code, we first store the HTML collection in the elements variable. Then, we iterate over each element in the collection using a for loop and add the class 'NewClass' to each individual element using the classList.add method.

huangapple
  • 本文由 发表于 2023年6月27日 21:29:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/76565389.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定