Is there a way in any browser to add/remove class names? For example, if I have a div with class names and I just want to remove/add 'name2' is there a way to do that?
Thanks,
rodchar
If you can use jQuery:
to remove:
$('#div1').removeClass('name2')
to add:
$('#div1').addClass('name2')
If you can't use jQuery, I found this url
http://snipplr.com/view/3561/addclass-removeclass-hasclass/
function hasClass(ele,cls) {
return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
}
function addClass(ele,cls) {
if (!this.hasClass(ele,cls)) ele.className += " "+cls;
}
function removeClass(ele,cls) {
if (hasClass(ele,cls)) {
var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');
ele.className=ele.className.replace(reg,' ');
}
}
Honestly, I haven't used the non-jquery approach but it seems enough
There will be a standard way to do this. HTML5 introduces the classList property, which works like this:
element.classList.add('foo');
element.classList.remove('bar');
if (element.classList.contains('bof'))
element.classList.toggle('zot');
Firefox 3.6 already has this feature and it's being worked on in WebKit.
Here is a pure-JS implementation:
// HTML5 classList-style methods
//
function Element_classList(element) {
if ('classList' in element)
return element.classList;
return {
item: function(ix) {
return element.className.trim().split(/\s+/)[ix];
},
contains: function(name) {
var classes= element.className.trim().split(/\s+/);
return classes.indexOf(name)!==-1;
},
add: function(name) {
var classes= element.className.trim().split(/\s+/);
if (classes.indexOf(name)===-1) {
classes.push(name);
element.className= classes.join(' ');
}
},
remove: function(name) {
var classes= element.className.trim().split(/\s+/);
var ix= classes.indexOf(name);
if (ix!==-1) {
classes.splice(ix, 1);
element.className= classes.join(' ');
}
},
toggle: function(name) {
var classes= element.className.trim().split(/\s+/);
var ix= classes.indexOf(name);
if (ix!==-1)
classes.splice(ix, 1);
else
classes.push(name);
element.className= classes.join(' ');
}
};
}
// Add ECMA262-5 string trim if not supported natively
//
if (!('trim' in String.prototype)) {
String.prototype.trim= function() {
return this.replace(/^\s+/, '').replace(/\s+$/, '');
};
}
// Add ECMA262-5 Array indexOf if not supported natively
//
if (!('indexOf' in Array.prototype)) {
Array.prototype.indexOf= function(find, from /*opt*/) {
for (var i= from || 0, n= this.length; i<n; i++)
if (i in this && this[i]===find)
return i;
return -1;
};
}
This does mean you have to write:
Element_classList(element).add('foo');
which is slightly less nice, but you'll get the advantage of the fast native implementation where avaialble.
its easy with javascript to change class name with any event for eg.
<script>
function changeClas()
{
document.getElementById('myDiv').className='myNewClass';
}
</script>
<div id="myDiv" onmouseover='changeClas()' class='myOldClass'> Hi There</div>
Related
How do you do jQuery’s hasClass with plain ol’ JavaScript? For example,
<body class="foo thatClass bar">
What’s the JavaScript way to ask if <body> has thatClass?
Simply use classList.contains():
if (document.body.classList.contains('thatClass')) {
// do some stuff
}
Other uses of classList:
document.body.classList.add('thisClass');
// $('body').addClass('thisClass');
document.body.classList.remove('thatClass');
// $('body').removeClass('thatClass');
document.body.classList.toggle('anotherClass');
// $('body').toggleClass('anotherClass');
Browser Support:
Chrome 8.0
Firefox 3.6
IE 10
Opera 11.50
Safari 5.1
classList Browser Support
You can check whether element.className matches /\bthatClass\b/.
\b matches a word break.
Or, you can use jQuery's own implementation:
var className = " " + selector + " ";
if ( (" " + element.className + " ").replace(/[\n\t]/g, " ").indexOf(" thatClass ") > -1 )
To answer your more general question, you can look at jQuery's source code on github or at the source for hasClass specifically in this source viewer.
The most effective one liner that
returns a boolean (as opposed to Orbling's answer)
Does not return a false positive when searching for thisClass on an element that has class="thisClass-suffix".
is compatible with every browser down to at least IE6
function hasClass( target, className ) {
return new RegExp('(\\s|^)' + className + '(\\s|$)').test(target.className);
}
// 1. Use if for see that classes:
if (document.querySelector(".section-name").classList.contains("section-filter")) {
alert("Grid section");
// code...
}
<!--2. Add a class in the .html:-->
<div class="section-name section-filter">...</div>
The attribute that stores the classes in use is className.
So you can say:
if (document.body.className.match(/\bmyclass\b/)) {
....
}
If you want a location that shows you how jQuery does everything, I would suggest:
http://code.jquery.com/jquery-1.5.js
Element.matches()
Instead of $(element).hasClass('example') in jQuery, you can use element.matches('.example') in plain JavaScript:
if (element.matches('.example')) {
// Element has example class ...
}
View Browser Compatibility
hasClass function:
HTMLElement.prototype.hasClass = function(cls) {
var i;
var classes = this.className.split(" ");
for(i = 0; i < classes.length; i++) {
if(classes[i] == cls) {
return true;
}
}
return false;
};
addClass function:
HTMLElement.prototype.addClass = function(add) {
if (!this.hasClass(add)){
this.className = (this.className + " " + add).trim();
}
};
removeClass function:
HTMLElement.prototype.removeClass = function(remove) {
var newClassName = "";
var i;
var classes = this.className.replace(/\s{2,}/g, ' ').split(" ");
for(i = 0; i < classes.length; i++) {
if(classes[i] !== remove) {
newClassName += classes[i] + " ";
}
}
this.className = newClassName.trim();
};
I use a simple/minimal solution, one line, cross browser, and works with legacy browsers as well:
/\bmyClass/.test(document.body.className) // notice the \b command for whole word 'myClass'
This method is great because does not require polyfills and if you use them for classList it's much better in terms of performance. At least for me.
Update: I made a tiny polyfill that's an all round solution I use now:
function hasClass(element,testClass){
if ('classList' in element) { return element.classList.contains(testClass);
} else { return new Regexp(testClass).exec(element.className); } // this is better
//} else { return el.className.indexOf(testClass) != -1; } // this is faster but requires indexOf() polyfill
return false;
}
For the other class manipulation, see the complete file here.
a good solution for this is to work with classList and contains.
i did it like this:
... for ( var i = 0; i < container.length; i++ ) {
if ( container[i].classList.contains('half_width') ) { ...
So you need your element and check the list of the classes. If one of the classes is the same as the one you search for it will return true if not it will return false!
This 'hasClass' function works in IE8+, FireFox and Chrome:
hasClass = function(el, cls) {
var regexp = new RegExp('(\\s|^)' + cls + '(\\s|$)'),
target = (typeof el.className === 'undefined') ? window.event.srcElement : el;
return target.className.match(regexp);
}
[Updated Jan'2021] A better way:
hasClass = (el, cls) => {
[...el.classList].includes(cls); //cls without dot
};
Use something like:
Array.prototype.indexOf.call(myHTMLSelector.classList, 'the-class');
if (document.body.className.split(/\s+/).indexOf("thatClass") !== -1) {
// has "thatClass"
}
Well all of the above answers are pretty good but here is a small simple function I whipped up. It works pretty well.
function hasClass(el, cn){
var classes = el.classList;
for(var j = 0; j < classes.length; j++){
if(classes[j] == cn){
return true;
}
}
}
What do you think about this approach?
<body class="thatClass anotherClass"> </body>
var bodyClasses = document.querySelector('body').className;
var myClass = new RegExp("thatClass");
var trueOrFalse = myClass.test( bodyClasses );
https://jsfiddle.net/5sv30bhe/
<div id="test" class="a1 a2 a5"></div>
var element = document.getElementById("test")
if (hasAnyOfTheseClasses(element, ["a1", "a6"])) {
//...
}
Looking for a simple, lightweight function to check if a function has any of the listed classes without jQuery or another library.
Such function would be easy to implement, but there should be a canonical, fastest and simplest answer people can just copy-paste.
This seems vampire-ish, but I'm asking this so googlers won't have to write it themselves.
Not a duplicate - the linked question checks for one class, this question asks for checking any of the classes.
A jQuery version exists here.
Here's a functional implementation using Array.some and Element.classList.contains.
function hasAnyClass(element, classes) {
return classes.some(function(c) {
return element.classList.contains(c);
});
}
var div = document.getElementById("test");
console.log(hasAnyClass(div, ["hi", "xyz"]));
console.log(hasAnyClass(div, ["xyz", "there"]));
console.log(hasAnyClass(div, ["xyz", "xyz"]));
<div id="test" class="hi there"></div>
Note that these functions are not supported on older versions of IE, and will require a shim/polyfill.
You could use a regex, not sure that it's purely better but at least more flexible since your current test relies too much on spaces being entered correctly.
function hasAnyOfTheseClasses(element, classes) {
var className = element.className;
for (var i = 0; i < classes.length; i++) {
var exp = new RegExp('\b'+classes[i] + '\b');
if(exp.test(className)) return true;
}
return false;
}
just create a loop that check if each value in your array is a class in your passed element
function hasAnyOfTheseClasses(elem, tofind) {
classes = elem.className.split(' ');
for(var x in tofind) {
var className = tofind[x];
if (classes.indexOf(className) == -1){
return false;
}
}
return true;
}
Here's my implementation:
function hasAnyOfTheseClasses(element, classes) {
for (var i = 0; i < classes.length; i++) {
if ((' ' + element.className + ' ').indexOf(' ' + classes[i] + ' ') > -1) {
return true;
}
}
return false;
}
It's not elegant or fast. Works though. Feel free to edit to improve.
Use the .classList property to get the list of classes of an element. Then you can use the .contains() method to test each of the classes.
function hasAnyOfTheseClass(element, classes) {
var classList = element.classList;
return classes.some(function(class) {
return classList.contains(class);
});
}
How about using Array.prototype.some() and Array.prototype.indexOf():
function hasAnyClass(el, classes) {
var elClasses = el.className.split(' ');
return classes.some(c => elClasses.indexOf(c) >= 0)
}
I'm looking for a fast and secure way to add and remove classes from an html element without jQuery.
It also should be working in early IE (IE8 and up).
Another approach to add the class to element using pure JavaScript
For adding class:
document.getElementById("div1").classList.add("classToBeAdded");
For removing class:
document.getElementById("div1").classList.remove("classToBeRemoved");
Note: but not supported in IE <= 9 or Safari <=5.0
The following 3 functions work in browsers which don't support classList:
function hasClass(el, className)
{
if (el.classList)
return el.classList.contains(className);
return !!el.className.match(new RegExp('(\\s|^)' + className + '(\\s|$)'));
}
function addClass(el, className)
{
if (el.classList)
el.classList.add(className)
else if (!hasClass(el, className))
el.className += " " + className;
}
function removeClass(el, className)
{
if (el.classList)
el.classList.remove(className)
else if (hasClass(el, className))
{
var reg = new RegExp('(\\s|^)' + className + '(\\s|$)');
el.className = el.className.replace(reg, ' ');
}
}
https://jaketrent.com/post/addremove-classes-raw-javascript/
For future friendliness, I second the recommendation for classList with polyfill/shim: https://developer.mozilla.org/en-US/docs/Web/API/Element/classList#wrapper
var elem = document.getElementById( 'some-id' );
elem.classList.add('some-class'); // Add class
elem.classList.remove('some-other-class'); // Remove class
elem.classList.toggle('some-other-class'); // Add or remove class
if ( elem.classList.contains('some-third-class') ) { // Check for class
console.log('yep!');
}
classList is available from IE10 onwards, use that if you can.
element.classList.add("something");
element.classList.remove("some-class");
I'm baffled none of the answers here prominently mentions the incredibly useful DOMTokenList.prototype.toggle method, which really simplifies alot of code.
E.g. you often see code that does this:
if (element.classList.contains(className) {
element.classList.remove(className)
} else {
element.classList.add(className)
}
This can be replaced with a simple call to
element.classList.toggle(className)
What is also very helpful in many situations, if you are adding or removing a class name based on a condition, you can pass that condition as a second argument. If that argument is truthy, toggle acts as add, if it's falsy, it acts as though you called remove.
element.classList.toggle(className, condition) // add if condition truthy, otherwise remove
To add class without JQuery just append yourClassName to your element className
document.documentElement.className += " yourClassName";
To remove class you can use replace() function
document.documentElement.className.replace(/(?:^|\s)yourClassName(?!\S)/,'');
Also as #DavidThomas mentioned you'd need to use the new RegExp() constructor if you want to pass class names dynamically to the replace function.
Add & Remove Classes (tested on IE8+)
Add trim() to IE (taken from: .trim() in JavaScript not working in IE)
if(typeof String.prototype.trim !== 'function') {
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, '');
}
}
Add and Remove Classes:
function addClass(element,className) {
var currentClassName = element.getAttribute("class");
if (typeof currentClassName!== "undefined" && currentClassName) {
element.setAttribute("class",currentClassName + " "+ className);
}
else {
element.setAttribute("class",className);
}
}
function removeClass(element,className) {
var currentClassName = element.getAttribute("class");
if (typeof currentClassName!== "undefined" && currentClassName) {
var class2RemoveIndex = currentClassName.indexOf(className);
if (class2RemoveIndex != -1) {
var class2Remove = currentClassName.substr(class2RemoveIndex, className.length);
var updatedClassName = currentClassName.replace(class2Remove,"").trim();
element.setAttribute("class",updatedClassName);
}
}
else {
element.removeAttribute("class");
}
}
Usage:
var targetElement = document.getElementById("myElement");
addClass(targetElement,"someClass");
removeClass(targetElement,"someClass");
A working JSFIDDLE:
http://jsfiddle.net/fixit/bac2vuzh/1/
Try this:
const element = document.querySelector('#elementId');
if (element.classList.contains("classToBeRemoved")) {
element.classList.remove("classToBeRemoved");
}
I'm using this simple code for this task:
CSS Code
.demo {
background: tomato;
color: white;
}
Javascript code
function myFunction() {
/* Assign element to x variable by id */
var x = document.getElementById('para);
if (x.hasAttribute('class') {
x.removeAttribute('class');
} else {
x.setAttribute('class', 'demo');
}
}
Updated JS Class Method
The add methods do not add duplicate classes and the remove method only removes class with exact string match.
const addClass = (selector, classList) => {
const element = document.querySelector(selector);
const classes = classList.split(' ')
classes.forEach((item, id) => {
element.classList.add(item)
})
}
const removeClass = (selector, classList) => {
const element = document.querySelector(selector);
const classes = classList.split(' ')
classes.forEach((item, id) => {
element.classList.remove(item)
})
}
addClass('button.submit', 'text-white color-blue') // add text-white and color-blue classes
removeClass('#home .paragraph', 'text-red bold') // removes text-red and bold classes
You can also do
elem.classList[test ? 'add' : 'remove']('class-to-add-or-remove');
Instead of
if (test) {
elem.classList.add('class-to-add-or-remove');
} else {
elem.classList.remove('class-to-add-or-remove');
}
When you remove RegExp from the equation you leave a less "friendly" code, but it still can be done with the (much) less elegant way of split().
function removeClass(classString, toRemove) {
classes = classString.split(' ');
var out = Array();
for (var i=0; i<classes.length; i++) {
if (classes[i].length == 0) // double spaces can create empty elements
continue;
if (classes[i] == toRemove) // don't include this one
continue;
out.push(classes[i])
}
return out.join(' ');
}
This method is a lot bigger than a simple replace() but at least it can be used on older browsers. And in case the browser doesn't even support the split() command it's relatively easy to add it using prototype.
Just in case someone needs to toggle class on click and remove on other elements in JS only. You can try to do following :
var accordionIcon = document.querySelectorAll('.accordion-toggle');
//add only on first element, that was required in my case
accordionIcon[0].classList.add('close');
for (i = 0; i < accordionIcon.length; i++) {
accordionIcon[i].addEventListener("click", function(event) {
for (i = 0; i < accordionIcon.length; i++) {
if(accordionIcon[i] !== event.target){
accordionIcon[i].classList.remove('close');
}
event.target.classList.toggle("close");
}
})
}
I am trying to go through an element and get all the attributes of that element to output them, for example an tag may have 3 or more attributes, unknown to me and I need to get the names and values of these attributes. I was thinking something along the lines of:
$(this).attr().each(function(index, element) {
var name = $(this).name;
var value = $(this).value;
//Do something with name and value...
});
Could anyone tell me if this is even possible, and if so what the correct syntax would be?
The attributes property contains them all:
$(this).each(function() {
$.each(this.attributes, function() {
// this.attributes is not a plain object, but an array
// of attribute nodes, which contain both the name and value
if(this.specified) {
console.log(this.name, this.value);
}
});
});
What you can also do is extending .attr so that you can call it like .attr() to get a plain object of all attributes:
(function(old) {
$.fn.attr = function() {
if(arguments.length === 0) {
if(this.length === 0) {
return null;
}
var obj = {};
$.each(this[0].attributes, function() {
if(this.specified) {
obj[this.name] = this.value;
}
});
return obj;
}
return old.apply(this, arguments);
};
})($.fn.attr);
Usage:
var $div = $("<div data-a='1' id='b'>");
$div.attr(); // { "data-a": "1", "id": "b" }
Here is an overview of the many ways that can be done, for my own reference as well as yours :) The functions return a hash of attribute names and their values.
Vanilla JS:
function getAttributes ( node ) {
var i,
attributeNodes = node.attributes,
length = attributeNodes.length,
attrs = {};
for ( i = 0; i < length; i++ ) attrs[attributeNodes[i].name] = attributeNodes[i].value;
return attrs;
}
Vanilla JS with Array.reduce
Works for browsers supporting ES 5.1 (2011). Requires IE9+, does not work in IE8.
function getAttributes ( node ) {
var attributeNodeArray = Array.prototype.slice.call( node.attributes );
return attributeNodeArray.reduce( function ( attrs, attribute ) {
attrs[attribute.name] = attribute.value;
return attrs;
}, {} );
}
jQuery
This function expects a jQuery object, not a DOM element.
function getAttributes ( $node ) {
var attrs = {};
$.each( $node[0].attributes, function ( index, attribute ) {
attrs[attribute.name] = attribute.value;
} );
return attrs;
}
Underscore
Also works for lodash.
function getAttributes ( node ) {
return _.reduce( node.attributes, function ( attrs, attribute ) {
attrs[attribute.name] = attribute.value;
return attrs;
}, {} );
}
lodash
Is even more concise than the Underscore version, but only works for lodash, not for Underscore. Requires IE9+, is buggy in IE8. Kudos to #AlJey for that one.
function getAttributes ( node ) {
return _.transform( node.attributes, function ( attrs, attribute ) {
attrs[attribute.name] = attribute.value;
}, {} );
}
Test page
At JS Bin, there is a live test page covering all these functions. The test includes boolean attributes (hidden) and enumerated attributes (contenteditable="").
A debugging script (jquery solution based on the answer above by hashchange)
function getAttributes ( $node ) {
$.each( $node[0].attributes, function ( index, attribute ) {
console.log(attribute.name+':'+attribute.value);
} );
}
getAttributes($(this)); // find out what attributes are available
with LoDash you could simply do this:
_.transform(this.attributes, function (result, item) {
item.specified && (result[item.name] = item.value);
}, {});
Using javascript function it is easier to get all the attributes of an element in NamedArrayFormat.
$("#myTestDiv").click(function(){
var attrs = document.getElementById("myTestDiv").attributes;
$.each(attrs,function(i,elem){
$("#attrs").html( $("#attrs").html()+"<br><b>"+elem.name+"</b>:<i>"+elem.value+"</i>");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="myTestDiv" ekind="div" etype="text" name="stack">
click This
</div>
<div id="attrs">Attributes are <div>
Simple solution by Underscore.js
For example: Get all links text who's parents have class someClass
_.pluck($('.someClass').find('a'), 'text');
Working fiddle
My suggestion:
$.fn.attrs = function (fnc) {
var obj = {};
$.each(this[0].attributes, function() {
if(this.name == 'value') return; // Avoid someone (optional)
if(this.specified) obj[this.name] = this.value;
});
return obj;
}
var a = $(el).attrs();
Here is a one-liner for you.
JQuery Users:
Replace $jQueryObject with your jQuery object. i.e $('div').
Object.values($jQueryObject.get(0).attributes).map(attr => console.log(`${attr.name + ' : ' + attr.value}`));
Vanilla Javascript Users:
Replace $domElement with your HTML DOM selector. i.e document.getElementById('demo').
Object.values($domElement.attributes).map(attr => console.log(`${attr.name + ' : ' + attr.value}`));
Cheers!!
Here is the function:
function lastmenuborder() {
var articleparent = document.getElementById('article').parentNode;
var articlestyle = window.getComputedStyle(articleparent,null).getPropertyValue('borderRadius');
alert (articlestyle);
}
I get no value, yet the css for the parent node is:
div#mainbody div.placeholder {
border-radius: 3px;
}
What would I have to change to return "3px"? All help greatly appreciated; I am still a newb at JavaScript.
For getPropertyValue(), you use hyphens instead of camelCase.
This works in Chrome...
.getPropertyValue('border-radius');
But Firefox seems to require specific corners using this syntax...
.getPropertyValue('border-top-left-radius');
getComputedStyle is not supported on IE8 below, to fix this use:
if (!window.getComputedStyle) {
window.getComputedStyle = function(el, pseudo) {
this.el = el;
this.getPropertyValue = function(prop) {
var re = /(\-([a-z]){1})/g;
if (prop == 'float') prop = 'styleFloat';
if (re.test(prop)) {
prop = prop.replace(re, function () {
return arguments[2].toUpperCase();
});
}
return el.currentStyle[prop] ? el.currentStyle[prop] : null;
}
return this;
}
}
var elem = window.getComputedStyle(document.getElementById('test'), "");
alert(elem.getPropertyValue("borderRadius"));