skip to Main Content

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');
}

2

Answers


  1. The issue in your code lies in the usage of getElementsByClassName. This function returns a collection of elements, not a single element, even if there is only one element with the specified class name. Therefore, you need to access the desired element from the collection before adding the class.

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

    In this code, getElementsByClassName returns a collection of elements with the specified class name. We check if the collection has any elements (elements.length > 0), and if it does, we access the first element by using elements[0] and then add the NewClass to it using classList.add('NewClass').

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search