0

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');
}
Yeppeuda
  • 55
  • 1
  • 8
  • 1
    it would be more helpful if you added the related html, url and so on – Carsten Løvbo Andersen Jun 27 '23 at 13:31
  • 1
    `document.getElementsByClassName('className')` returns an HTML Collection, not a single element. Use your debugging tools to examine what that method returns. – mykaf Jun 27 '23 at 13:33
  • As tagged [tag:jquery] (despite not having jquery in the question): `$(".className").toggleClass("newClass", location.href.indexOf('url') > -1)` – freedomn-m Jun 27 '23 at 13:47

1 Answers1

1

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('url') > -1) { 
  var elements = document.getElementsByClassName('className');
  for (var i = 0; i < elements.length; i++) {
    elements[i].classList.add('NewClass');
  }
}

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.

Tned
  • 69
  • 1
  • 5