简体   繁体   中英

Get elements by class name and change class name

I have the following:

<div id="elementor-tab-title-1141" class="elementor-tab-title elementor-active"> 
     ...some stuff... 
</div>

I need a JavaScript code to look for all elements with that class, and remove the "elementor-active". So the code, after the JavaScript runs on page load, should look like this:

<div id="elementor-tab-title-1141" class="elementor-tab-title"> 
         ...some stuff... 
</div>

Here is what I tried:

function changeClass()
{
    var classNameArray= document.getElementsByClassName("elementor-tab-title elementor-active");

    for(var i = (classNameArray.length - 1); i >= 0; i--)
    {
        classNameArray[i].innerHTML = 
        getClassName(classNameArray[i].innerHTML);
        classNameArray[i].className = "elementor-tab-title";
    }
}

Thanks!

You can use querySelectorAll() to target all the elements, then loop through them to remove class using classList.remove() from the element:

 var elList = [].slice.call(document.querySelectorAll('.elementor-tab-title')); elList.forEach(function(el){ el.classList.remove('elementor-active'); }); 
 .elementor-tab-title{ color: green; } .elementor-active{ color: red; } 
 <div id="elementor-tab-title-1141" class="elementor-tab-title elementor-active"> ...some stuff... </div> <div id="elementor-tab-title-1142" class="elementor-tab-title elementor-active"> ...some stuff2... </div> <div id="elementor-tab-title-1143" class="elementor-tab-title elementor-active"> ...some stuff3... </div> 

Follow the below steps

  • Use querySelectorAll() to get all the elements with that class
  • Then use forEach() loop on all the elements
  • Use classList.remove() to remove that particular class

 [...document.querySelectorAll('elementor-tab-title,.elementor-active')].forEach(x => x.classList.remove('elementor-active')) console.log(document.body.innerHTML) 
 <div id="elementor-tab-title-1141" class="elementor-tab-title elementor-active"> ...some stuff... </div> 

Using jQuery

You can do that bit easier using jQuery removeClass()

 $('.elementor-tab-title').removeClass('elementor-active'); console.log(document.body.innerHTML) 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="elementor-tab-title-1141" class="elementor-tab-title elementor-active"> ...some stuff... </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM