Is there a way to add a class to an element (using pure javascript) that does not have an ID, but has some existing classes? If I had:
<div class="rightAlign pushDown">...</div>
How could I add a class to make it like this
<div class="rightAlign pushDown redOutline">...</div>
This is just a simple example. The reason for adding another class and not changing the original class in CSS or changing the class altogether with javascript is that I am dealing with elements created by Dojo. I just need to access something that has no convenient ID to grab a hold of.
Keep in mind I am working in javascript and Dojo, I can not use jQuery at all...
The dojo way would be as:
dojo.query(".rightAlign.pushDown").addClass("redOutline");
This will add the class to add elements with those two classes
var elements = document.getElementsByClassName("existing_class");
elements[0].className += " new_class";
If you want to add a class to all elements with a specified class then use a loop:
for(var i = 0; i < elements.length; i++){
elements[i].className =+ " new_class";
}
I think getElementsByClassName doesn't work in old IE versions though.
EDIT:
Polyfill for IE support
Related
I have a Wordpress site with a background in the header inside of a class.
I'm tring to write a bit of JS to change this background image depending on a hashtag. The Hashtag script is working but the change BG bit isn't - please help... :-(
The script I've writen is:
document.getElementsByClassName("eut-bg-image").style.backgroundImage = "url(https://boutiqueballer.com/wp/wp-content/uploads/2017/10/chanel.jpg)";
})();
getElementsByClassName yields a collection of elements. The individual elements in the collection have the style property, not the collection itself. If you are targeting just one element, you can access it by index:
document.getElementsByClassName('eut-bg-image')[0].style.backgroundImage = ...;
If you are targeting several elements, you may iterate over them:
var elements = document.getElementsByClassName('eut-bg-image');
for(var i = 0; i < elements.length; i++)
elements[i].style.backgroundImage = ...;
Alternatively, you may use document.querySelector, depending on which level of browser compatibility you need. You can then distinguish between document.querySelectorAll if you want a collection, or docment.querySelector if you want only the first match. Accepts a CSS selector:
document.querySelector('.eut-bg-image').style.backgroundImage = ...;
I'm working on a theme in WordPress I want to add a new class to an element without removing existing class in this theme there is a place
to add javascript code in theme option with my new class this button
will toggle to a form here is the code that I want to add my new
class into it.
<span>ّFORM</span>
jQuery is included by default in WordPress, this can be done by:
$('.button-5509e751af089').toggleClass('myClass');
With regular JavaScript, I would do the following:
document.getElementsByClassName('button-5509e751af089')[0].classList.toggle('myClass');
These method will only toggle the class of the first item, unlike the jQuery answer.
More information on classList here
If you would like the value of the class to be from an input, replace 'myClass' with the following
jQuery:
$('input.myInput').val();
JavaScript:
document.getElementsByClassName('inputClassHere')[0].value
EDIT: One can also use .querySelector(".myClass") instead of .getElementsByClassName('myClass')[0]
it depends on if you want to add this class to all buttons on the page or just one. assuming you want all buttons, you would do the following:
var elements = document.querySelectorAll(".mk-button");
for(var i = 0; i < elements.length; ++i) {
var el = elements[i]
el.className = el.className + " new-class-here";
}
Is it possible to add an HTML ID via the browser console using DOM Manipulation?
For example, suppose I am dealing with the following element:
<div class="elementClass">
I can fetch via DOM with something like:
document.getElementsByClassName("elementClass");
However, is it possible to add an attribute via this type of method? If I inspect the element with chrome I can do it manually, but I am wondering if it's possible to inject that ID via JavaScript.
Thanks!
You can do:
document.getElementsByClassName("elementClass")[0].setAttribute("id", "some ID");
Yes you can modify attributes of an object (HTMLElement) via javascript
getElementsByclassName returns an array, simply iterate through the list and set the attributes you wish.
var elements = document.getElementsByClassName("elementClass");
for(var I = 0; I < elements.length; I++)
element[I].id = "element" + I;
Then you could access any of those elements with that class via
var element = document.getElementById("element" + 0); //Gets First Element
Sure.
document.getElementsByClassName('elementClass')[0].id = 'someID';
or
document.getElementsByClassName('elementClass')[0].setAttribute('id', 'someID');
Just know that if you grab elements using getElementsByClassName then it will return an array of elements (assuming any elements with the matching class exist) so modifying the array won't give you the result you want.
setAttribute() method on the DOM element should work just fine.
HTML
<div class="elementClass">
This is the content of elementClass
</div>
<button onclick="buttonClicked()">Click to add attribute id red to elementClass</button>
Javascript
function buttonClicked(){
document.getElementsByClassName("elementClass")[0].setAttribute("id", "red");
}
CSS
#red {
background-color: red;
}
PLAYGROUND
Note that manipulating the class attribute causes the browser to reflow, therefore it is worth mentioning to use setAttribute() wisely to not cause performance issue.
i'm running a contact-form-plugin on my wordpress installation. everything works fine but i want to style my form a little bit more. to do it like this i have to style some DIVs (which the plugin is processing) in a different way. the problem is: all DIV-containers have no IDs or classes! everything is processed by the plugin and my PHP-skills are like zero so i have to deal with this "naked" DIVs ;-)
the question is: is it possible to add serially numbered classes to each DIV on the current site via javascript?
thanks so far and i hope you get waht i mean (sorry for that shitty english)!
Yet another way, passing a callback to .attr [docs]:
$('div').attr('class', function(i) {
return 'someClass' + i;
});
Though you could also use this for IDs instead, since each class will be unique.
Note that you don't have to use IDs or classes to select elements, there are a number of selectors and traversal methods with which you can get a reference to the elements you want.
To prevent overriding existing classes, either select only the elements with no class or somehow narrow down the selection of divs to only those you want:
$('div:not([class])')
or use .addClass [docs] instead of .attr:
$('div').addClass(function(i) {
return 'someClass' + i;
});
You need something like this,
Live Demo
$('div').each(function(i, item){
$(this).attr('class', "YourClass" + i); //You can replace i with some other variable if required and increment it.
});
You could do this:
var divs = document.getElementsByTagName("div");
var className = "myClass";
for( var i = 0, max = divs.length; i< max; i++ ){
divs[i].setAttribute("class",className + i.toString());
}
Suppose a HTML element's id is known, so the element can be refereced using:
document.getElementById(element_id);
Does a native Javascript function exist that can be used to append a CSS class to that element?
var element = document.getElementById(element_id);
element.className += " " + newClassName;
Voilà. This will work on pretty much every browser ever. The leading space is important, because the className property treats the css classes like a single string, which ought to match the class attribute on HTML elements (where multiple classes must be separated by spaces).
Incidentally, you're going to be better off using a Javascript library like prototype or jQuery, which have methods to do this, as well as functions that can first check if an element already has a class assigned.
In prototype, for instance:
// Prototype automatically checks that the element doesn't already have the class
$(element_id).addClassName(newClassName);
See how much nicer that is?!
Adding class using element's classList property:
element.classList.add('my-class-name');
Removing:
element.classList.remove('my-class-name');
classList is a convenient alternative to accessing an element's list of classes.. see http://developer.mozilla.org/en-US/docs/Web/API/Element.classList.
Not supported in IE < 10
When an element already has a class name defined, its influence on the element is tied to its position in the string of class names.
Later classes override earlier ones, if there is a conflict.
Adding a class to an element ought to move the class name to the sharp end of the list, if it exists already.
document.addClass= function(el, css){
var tem, C= el.className.split(/\s+/), A=[];
while(C.length){
tem= C.shift();
if(tem && tem!= css) A[A.length]= tem;
}
A[A.length]= css;
return el.className= A.join(' ');
}
You should be able to set the className property of the element. You could do a += to append it.
addClass=(selector,classes)=>document.querySelector(selector).classList(...classes.split(' '));
This will add ONE class or MULTIPLE classes :
addClass('#myDiv','back-red'); // => Add "back-red" class to <div id="myDiv"/>
addClass('#myDiv','fa fa-car') //=>Add two classes to "div"
you could use setAttribute.
Example:
For adding one class:
document.getElementById('main').setAttribute("class","classOne");
For multiple classes:
document.getElementById('main').setAttribute("class", "classOne classTwo");