Reputation: 181
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>
Upvotes: 2
Views: 4172
Reputation: 42044
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>
Upvotes: 3
Reputation: 45
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);
}
Upvotes: 0
Reputation: 9878
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" );
Upvotes: 0
Reputation: 3866
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 changing css class to div
how to change class name of an element by jquery
Upvotes: 1
Reputation: 500
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)
}
Upvotes: 0