- This topic is empty.
-
AuthorPosts
-
March 20, 2015 at 2:35 am #9684
Deprecated: Function seems_utf8 is deprecated since version 6.9.0! Use wp_is_valid_utf8() instead. in /home/u337135316/domains/bzotech.com/public_html/wp-includes/functions.php on line 6131
Deprecated: Function seems_utf8 is deprecated since version 6.9.0! Use wp_is_valid_utf8() instead. in /home/u337135316/domains/bzotech.com/public_html/wp-includes/functions.php on line 6131
David Hoang
KeymasterJust thought I’d throw this in:
function inArray(val, ary){ for(var i=0,l=ary.length; i<l; i++){ if(ary[i] === val){ return true; } } return false; } function removeClassName(classNameS, fromElement){ var x = classNameS.split(/\s/), s = fromElement.className.split(/\s/), r = []; for(var i=0,l=s.length; i<l; i++){ if(!iA(s[i], x))r.push(s[i]); } fromElement.className = r.join(' '); } function addClassName(classNameS, toElement){ var s = toElement.className.split(/\s/); s.push(c); toElement.className = s.join(' '); }October 28, 2015 at 7:00 am #9697
Deprecated: Function seems_utf8 is deprecated since version 6.9.0! Use wp_is_valid_utf8() instead. in /home/u337135316/domains/bzotech.com/public_html/wp-includes/functions.php on line 6131
Deprecated: Function seems_utf8 is deprecated since version 6.9.0! Use wp_is_valid_utf8() instead. in /home/u337135316/domains/bzotech.com/public_html/wp-includes/functions.php on line 6131
David Hoang
KeymasterHere’s a toggleClass to toggle/add/remove a class on an element:
// If newState is provided add/remove theClass accordingly, otherwise toggle theClass function toggleClass(elem, theClass, newState) { var matchRegExp = new RegExp('(?:^|\\s)' + theClass + '(?!\\S)', 'g'); var add=(arguments.length>2 ? newState : (elem.className.match(matchRegExp) == null)); elem.className=elem.className.replace(matchRegExp, ''); // clear all if (add) elem.className += ' ' + theClass; }See the JSFiddle.
Also see my answer here for creating a new class dynamically.
November 4, 2015 at 5:57 am #9699
Deprecated: Function seems_utf8 is deprecated since version 6.9.0! Use wp_is_valid_utf8() instead. in /home/u337135316/domains/bzotech.com/public_html/wp-includes/functions.php on line 6131
Deprecated: Function seems_utf8 is deprecated since version 6.9.0! Use wp_is_valid_utf8() instead. in /home/u337135316/domains/bzotech.com/public_html/wp-includes/functions.php on line 6131
David Hoang
KeymasterChange an element’s class in vanilla JavaScript with Internet Explorer 6 support
You may try to use the node
attributesproperty to keep compatibility with old browsers, even Internet Explorer 6:function getClassNode(element) { for (var i = element.attributes.length; i--;) if (element.attributes[i].nodeName === 'class') return element.attributes[i]; } function removeClass(classNode, className) { var index, classList = classNode.value.split(' '); if ((index = classList.indexOf(className)) > -1) { classList.splice(index, 1); classNode.value = classList.join(' '); } } function hasClass(classNode, className) { return classNode.value.indexOf(className) > -1; } function addClass(classNode, className) { if (!hasClass(classNode, className)) classNode.value += ' ' + className; } document.getElementById('message').addEventListener('click', function() { var classNode = getClassNode(this); var className = hasClass(classNode, 'red') && 'blue' || 'red'; removeClass(classNode, 'red'); removeClass(classNode, 'blue'); addClass(classNode, className); }).red { color: red; } .red:before { content: 'I am red! '; } .red:after { content: ' again'; } .blue { color: blue; } .blue:before { content: 'I am blue! ' }<span id="message" class="">Click me</span>April 21, 2017 at 2:50 am #9685
Deprecated: Function seems_utf8 is deprecated since version 6.9.0! Use wp_is_valid_utf8() instead. in /home/u337135316/domains/bzotech.com/public_html/wp-includes/functions.php on line 6131
Deprecated: Function seems_utf8 is deprecated since version 6.9.0! Use wp_is_valid_utf8() instead. in /home/u337135316/domains/bzotech.com/public_html/wp-includes/functions.php on line 6131
David Hoang
KeymasterJust use
myElement.classList="new-class"unless you need to maintain other existing classes in which case you can use theclassList.add, .removemethods.var doc = document; var divOne = doc.getElementById("one"); var goButton = doc.getElementById("go"); goButton.addEventListener("click", function() { divOne.classList="blue"; });div{ min-height: 48px; min-width: 48px; } .bordered{ border: 1px solid black; } .green{ background: green; } .blue{ background: blue; }<button id="go">Change Class</button> <div id="one" class="bordered green"> </div>May 29, 2017 at 1:29 am #9691
Deprecated: Function seems_utf8 is deprecated since version 6.9.0! Use wp_is_valid_utf8() instead. in /home/u337135316/domains/bzotech.com/public_html/wp-includes/functions.php on line 6131
Deprecated: Function seems_utf8 is deprecated since version 6.9.0! Use wp_is_valid_utf8() instead. in /home/u337135316/domains/bzotech.com/public_html/wp-includes/functions.php on line 6131
David Hoang
KeymasterOK, I think in this case you should use jQuery or write your own Methods in pure JavaScript. My preference is adding my own methods rather than injecting all jQuery to my application if I don’t need that for other reasons.
I’d like to do something like below as methods to my JavaScript framework to add few functionalities which handle adding classes, deleting classes, etc. Similar to jQuery, this is fully supported in IE9+. Also my code is written in ES6, so you need to make sure your browser support it or you using something like Babel, otherwise need to use ES5 syntax in your code. Also in this way, we finding element via ID, which means the element needs to have an ID to be selected:
// Simple JavaScript utilities for class management in ES6 var classUtil = { addClass: (id, cl) => { document.getElementById(id).classList.add(cl); }, removeClass: (id, cl) => { document.getElementById(id).classList.remove(cl); }, hasClass: (id, cl) => { return document.getElementById(id).classList.contains(cl); }, toggleClass: (id, cl) => { document.getElementById(id).classList.toggle(cl); } }And you can simply use them as below. Imagine your element has id of ‘id’ and class of ‘class’. Make sure you pass them as a string. You can use the utility as below:
classUtil.addClass('myId', 'myClass'); classUtil.removeClass('myId', 'myClass'); classUtil.hasClass('myId', 'myClass'); classUtil.toggleClass('myId', 'myClass');September 21, 2018 at 9:23 am #9689
Deprecated: Function seems_utf8 is deprecated since version 6.9.0! Use wp_is_valid_utf8() instead. in /home/u337135316/domains/bzotech.com/public_html/wp-includes/functions.php on line 6131
Deprecated: Function seems_utf8 is deprecated since version 6.9.0! Use wp_is_valid_utf8() instead. in /home/u337135316/domains/bzotech.com/public_html/wp-includes/functions.php on line 6131
David Hoang
KeymasterclassListDOM API:A very convenient manner of adding and removing classes is the
classListDOM API. This API allows us to select all classes of a specific DOM element in order to modify the list using JavaScript. For example:const el = document.getElementById("main"); console.log(el.classList);<div class="content wrapper animated" id="main"></div>We can observe in the log that we are getting back an object with not only the classes of the element, but also many auxiliary methods and properties. This object inherits from the interface DOMTokenList, an interface which is used in the DOM to represent a set of space separated tokens (like classes).
Example:
const el = document.getElementById('container'); function addClass () { el.classList.add('newclass'); } function replaceClass () { el.classList.replace('foo', 'newFoo'); } function removeClass () { el.classList.remove('bar'); }button{ margin: 20px; } .foo{ color: red; } .newFoo { color: blue; } .bar{ background-color: powderblue; } .newclass{ border: 2px solid green; }<div class="foo bar" id="container"> "Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas </div> <button onclick="addClass()">AddClass</button> <button onclick="replaceClass()">ReplaceClass</button> <button onclick="removeClass()">removeClass</button>February 6, 2019 at 2:02 am #9690
Deprecated: Function seems_utf8 is deprecated since version 6.9.0! Use wp_is_valid_utf8() instead. in /home/u337135316/domains/bzotech.com/public_html/wp-includes/functions.php on line 6131
Deprecated: Function seems_utf8 is deprecated since version 6.9.0! Use wp_is_valid_utf8() instead. in /home/u337135316/domains/bzotech.com/public_html/wp-includes/functions.php on line 6131
David Hoang
KeymasterYes, there are many ways to do this. In ES6 syntax we can achieve easily. Use this code toggle add and remove class.
const tabs=document.querySelectorAll('.menu li'); for(let tab of tabs){ tab.onclick = function(){ let activetab = document.querySelectorAll('li.active'); activetab[0].classList.remove('active') tab.classList.add('active'); } }body { padding: 20px; font-family: sans-serif; } ul { margin: 20px 0; list-style: none; } li { background: #dfdfdf; padding: 10px; margin: 6px 0; cursor: pointer; } li.active { background: #2794c7; font-weight: bold; color: #ffffff; }<i>Please click an item:</i> <ul class="menu"> <li class="active"><span>Three</span></li> <li><span>Two</span></li> <li><span>One</span></li> </ul>February 22, 2019 at 10:22 am #9686
Deprecated: Function seems_utf8 is deprecated since version 6.9.0! Use wp_is_valid_utf8() instead. in /home/u337135316/domains/bzotech.com/public_html/wp-includes/functions.php on line 6131
Deprecated: Function seems_utf8 is deprecated since version 6.9.0! Use wp_is_valid_utf8() instead. in /home/u337135316/domains/bzotech.com/public_html/wp-includes/functions.php on line 6131
David Hoang
KeymasterTL;DR:
document.getElementById('id').className = 'class'OR
document.getElementById('id').classList.add('class'); document.getElementById('id').classList.remove('class');That’s it.
And, if you really want to know the why and educate yourself then I suggest reading Peter Boughton’s answer. It’s perfect.
Note:
This is possible with (document or event):
getElementById()getElementsByClassName()querySelector()querySelectorAll()
April 14, 2019 at 10:51 am #9692
Deprecated: Function seems_utf8 is deprecated since version 6.9.0! Use wp_is_valid_utf8() instead. in /home/u337135316/domains/bzotech.com/public_html/wp-includes/functions.php on line 6131
Deprecated: Function seems_utf8 is deprecated since version 6.9.0! Use wp_is_valid_utf8() instead. in /home/u337135316/domains/bzotech.com/public_html/wp-includes/functions.php on line 6131
David Hoang
KeymasterTry:
element.className='second'function change(box) { box.className='second' }.first { width: 70px; height: 70px; background: #ff0 } .second { width: 150px; height: 150px; background: #f00; transition: 1s }<div onclick="change(this)" class="first">Click me</div>August 22, 2019 at 6:28 am #9693
Deprecated: Function seems_utf8 is deprecated since version 6.9.0! Use wp_is_valid_utf8() instead. in /home/u337135316/domains/bzotech.com/public_html/wp-includes/functions.php on line 6131
Deprecated: Function seems_utf8 is deprecated since version 6.9.0! Use wp_is_valid_utf8() instead. in /home/u337135316/domains/bzotech.com/public_html/wp-includes/functions.php on line 6131
David Hoang
Keymaster
THE OPTIONS.
Here is a little style vs. classList examples to get you to see what are the options you have available and how to use
classListto do what you want.stylevs.classListThe difference between
styleandclassListis that withstyleyou’re adding to the style properties of the element, butclassListis kinda controlling the class(es) of the element (add,remove,toggle,contain), I will show you how to use theaddandremovemethod since those are the popular ones.
Style Example
If you want to add
margin-topproperty into an element, you would do in such:// Get the Element const el = document.querySelector('#element'); // Add CSS property el.style.margintop = "0px" el.style.margintop = "25px" // This would add a 25px to the top of the element.
classList Example
Let say we have a
<div class="class-a class-b">, in this case, we have 2 classes added to our div element already,class-aandclass-b, and we want to control what classesremoveand what class toadd. This is whereclassListbecomes handy.Remove
class-b// Get the Element const el = document.querySelector('#element'); // Remove class-b style from the element el.classList.remove("class-b")Add
class-c// Get the Element const el = document.querySelector('#element'); // Add class-b style from the element el.classList.add("class-c")
September 4, 2019 at 3:32 am #9687
Deprecated: Function seems_utf8 is deprecated since version 6.9.0! Use wp_is_valid_utf8() instead. in /home/u337135316/domains/bzotech.com/public_html/wp-includes/functions.php on line 6131
Deprecated: Function seems_utf8 is deprecated since version 6.9.0! Use wp_is_valid_utf8() instead. in /home/u337135316/domains/bzotech.com/public_html/wp-includes/functions.php on line 6131
David Hoang
Keymasterfunction classed(el, class_name, add_class) { const re = new RegExp("(?:^|\\s)" + class_name + "(?!\\S)", "g"); if (add_class && !el.className.match(re)) el.className += " " + class_name else if (!add_class) el.className = el.className.replace(re, ''); }Using Peter Boughton’s answer, here is a simple cross-browser function to add and remove class.
Add class:
classed(document.getElementById("denis"), "active", true)Remove class:
classed(document.getElementById("denis"), "active", false)March 20, 2020 at 12:25 pm #9688
Deprecated: Function seems_utf8 is deprecated since version 6.9.0! Use wp_is_valid_utf8() instead. in /home/u337135316/domains/bzotech.com/public_html/wp-includes/functions.php on line 6131
Deprecated: Function seems_utf8 is deprecated since version 6.9.0! Use wp_is_valid_utf8() instead. in /home/u337135316/domains/bzotech.com/public_html/wp-includes/functions.php on line 6131
David Hoang
KeymasterThere is a property, className, in JavaScript to change the name of the class of an HTML element. The existing class value will be replaced with the new one, that you have assigned in className.
<!DOCTYPE html> <html> <head> <title>How can I change the class of an HTML element in JavaScript?</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> </head> <body> <h1 align="center"><i class="fa fa-home" id="icon"></i></h1><br /> <center><button id="change-class">Change Class</button></center> <script> var change_class = document.getElementById("change-class"); change_class.onclick = function() { var icon=document.getElementById("icon"); icon.className = "fa fa-gear"; } </script> </body> </html>Credit – How To Change Class Name of an HTML Element in JavaScript
May 3, 2020 at 11:05 am #9695
Deprecated: Function seems_utf8 is deprecated since version 6.9.0! Use wp_is_valid_utf8() instead. in /home/u337135316/domains/bzotech.com/public_html/wp-includes/functions.php on line 6131
Deprecated: Function seems_utf8 is deprecated since version 6.9.0! Use wp_is_valid_utf8() instead. in /home/u337135316/domains/bzotech.com/public_html/wp-includes/functions.php on line 6131
David Hoang
KeymasterThe OP question was How can I change an element’s class with JavaScript?
Modern browsers allow you to do this with one line of JavaScript:
document.getElementById('id').classList.replace('span1', 'span2')The
classListattribute provides a DOMTokenList which has a variety of methods. You can operate on an element’s classList using simple manipulations like add(), remove() or replace(). Or get very sophisticated and manipulate classes like you would an object or Map with keys(), values(), and entries().Peter Boughton’s answer is a great one, but it’s now over a decade old. All modern browsers now support DOMTokenList – see https://caniuse.com/#search=classList and even Internet Explorer 11 supports some DOMTokenList methods.
September 5, 2021 at 4:50 am #9707
Deprecated: Function seems_utf8 is deprecated since version 6.9.0! Use wp_is_valid_utf8() instead. in /home/u337135316/domains/bzotech.com/public_html/wp-includes/functions.php on line 6131
Deprecated: Function seems_utf8 is deprecated since version 6.9.0! Use wp_is_valid_utf8() instead. in /home/u337135316/domains/bzotech.com/public_html/wp-includes/functions.php on line 6131
David Hoang
Keymaster4 actions possible: Add, Remove, Check, and Toggle
Let’s see multiple ways for each action.
1. Add class
Method 1: Best way to add a class in the modern browser is using
classList.add()method of element.-
Case 1: Adding single class
function addClass() { let element = document.getElementById('id1'); // adding class element.classList.add('beautify'); } -
Case 2: Adding multiple class
To add multiple classes saperate classes by a comma in the
add()methodfunction addClass() { let element = document.getElementById('id1'); // adding multiple class element.classList.add('class1', 'class2', 'class3'); }
Method 2 – You can also add classes to HTML elements using
classNameproperty.- Case 1: Overwriting pre-existing classes
When you assign a new class to theclassNameproperty it overwrites the previous class.function addClass() { let element = document.getElementById('id1'); // adding multiple class element.className = 'beautify'; } - Case 2: Adding class without overwrite
Use+=operator for class not to overwrite previous classes. Also, add an extra space before the new class.function addClass() { let element = document.getElementById('id1'); // adding single multiple class element.className += ' beautify'; // adding multiple classes element.className += ' class1 class2 class3'; }
2. Remove class
Method 1 – The best way to remove a class from an element is the
classList.remove()method.-
Case 1: Remove single class
Just pass the class name you want to remove from the element in the method.
function removeClass() { let element = document.getElementById('id1'); // removing class element.classList.remove('beautify'); } -
Case 2: Remove multiple class
Pass multiple classes separated by a comma.
function removeClass() { let element = document.getElementById('id1'); // removing class element.classList.remove('class1', 'class2', 'class3'); }
Method 2 – You can also remove class using
classNamemethod.- Case 1: Removing single class
If the element has only 1 class and you want to remove it then just assign an empty string to theclassNamemethod.function removeClass() { let element = document.getElementById('id1'); // removing class element.className = ''; } - Case 2: Removing multiple class
If the element has multiple classes first get all classes from the element using theclassNameproperty and use replace method and replace desired classes with an empty string and finally assign it to element’sclassNameproperty.function removeClass() { let element = document.getElementById('id1'); // removing class element.className = element.className.replace('class1', ''); }
3. Checking class
To check if a class exists in the element you can simply use
classList.contains()method. It returnstrueif the class exists else returns false.function checkClass() { let element = document.getElementById('id1'); // checking class if(element.classList.contains('beautify') { alert('Yes! class exists'); } }
4. Toggle class
To toggle a class use
classList.toggle()method.function toggleClass() { let element = document.getElementById('id1'); // toggle class element.classList.toggle('beautify'); }September 10, 2021 at 11:57 am #9694
Deprecated: Function seems_utf8 is deprecated since version 6.9.0! Use wp_is_valid_utf8() instead. in /home/u337135316/domains/bzotech.com/public_html/wp-includes/functions.php on line 6131
Deprecated: Function seems_utf8 is deprecated since version 6.9.0! Use wp_is_valid_utf8() instead. in /home/u337135316/domains/bzotech.com/public_html/wp-includes/functions.php on line 6131
David Hoang
KeymasterFor IE v6-9 (in which
classListis not supported and you don’t want to use polyfills):var elem = document.getElementById('some-id'); // don't forget the extra space before the class name var classList = elem.getAttribute('class') + ' other-class-name'; elem.setAttribute('class', classList); -
AuthorPosts
- You must be logged in to reply to this topic.