2

How do I add a class to a specific class on a specific page using pure Javascript? I've played around with a number of different code-snippets but can't manage to get anything to work. I'm looking for something like the following:

<script>
    if (window.location.href == 'http://specific-page.com') {
      $(somecode).find('existingClass').addClass('newClass');
   };
</script>
2
  • Can't you replace somecode with the element type i.e. div, input, ul, li? Commented Feb 10, 2017 at 15:08
  • 3
    Did you try using find('.existingClass'). You need to specify selector. I suppose 'existingClass' is a class, so you need '.' in front of it Commented Feb 10, 2017 at 15:09

5 Answers 5

3

You can use querySelectorAll plus NodeList.forEach().

Moreover, you can take a look to the Element.classList methods.

The snippet:

//
// For test purposes only
//
window.location.href1 = 'http://specific-page.com';


if (window.location.href1 == 'http://specific-page.com') {
  document.querySelectorAll('#myDiv .existingClass').forEach(function(ele, idx) {
    ele.classList.add('newClass');
  });
};
.existingClass {
  height: 30px;
  background-color: red;
}
.newClass {
  border-style: dotted;
}
<div id="myDiv">
    <p class="existingClass">Thbis is a sample string</p>
</div>

Sign up to request clarification or add additional context in comments.

Comments

1

It should work:

<script>
  if (window.location.href == 'http://specific-page.com') {
    $('.existingClass').addClass('newClass');
  };
</script>

What you have to do is to use the class you are looking for as a selector, in this case it is ".existingClass".

There are many other ways to do it depending on what you are trying to acchive.

Other post:

jquery change class name

jQuery changing css class to div

how to change class name of an element by jquery

2 Comments

The OP says "pure javascript". I'm assuming he doesn't want a jQuery solution.
He has posted as an example a jQuery code. I assumed OP was referencing jQuery as JavaScript.
0

If you want to do this in Vannila JS, then you can use the code from below. It doesn't use jQuery.

if ( window.location.href == 'http://specific-page.com' ) {
  var el = document.getElementsByClassName("currentClass")[0];
  var newClass = el.getAttribute("class");
  newClass += " myNewClass"; 
  el.setAttribute("class", newClass)
  console.log(el)
  }

Comments

0

You can use the setAttribute to set the Attribute class to a new value. In the value, you can add the new class to the existing class value. Also, the getElementsByClassName returns the Elements list, so you need to select the right element Appropriately. I am using the element at first index below.

var elements = document.getElementsByClassName("existingClass");
elements[0].setAttribute( "class", "existingClass" + " newClass" );

Comments

0

this is the easiest but get elements by classname will fail on some browsers like older i.e.

compatibility can be found here - https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName#Browser_compatibility

 // JavaScript Document

window.onload = init;
var divsWithClass = null;


function init() {
    if (window.location.href.indexOf("some value you care about") >= 0) {
        this.divsWithClass = document.getElementsByClassName("Some Class Name");
        var index = 0;
        while (index < divsWithClass.length) {
            divsWithClass[index].className += " newClass";
            index++;
        }
    }
    console.log(divsWithClass);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.