简体   繁体   中英

Removing a class from an HTML element using JavaScript

I am attempting to remove a class from an html tag using JavaScript but I have no idea where to start. I have searched but to no avail. While I am decently fluent in jQuery, I am not in JavaScript and I need to use JavaScript in this instance Anything I have found thus far would need to be adjusted for my own use, which I have not been successful at. Hopefully someone can explain it in a fool-proof way.

The element the class is attached to is the "ul" tag. The class is named "nojavaScript" and is only applied to this single instance of the "ul" tag. While as I said the class is only used once in the page, the "ul" tag is used in other instances with different classes or ids. If it would make it easier for the JavaScript, I can change the class to an id.

I hope I have given you enough to go on. I will include an example of the html code below.

<ul id="lines_list" class="nojavaScript"></ul>

As I mentioned, if it's easier to remove an id than a class, I can make the current id a class, and the current class an id. But essentially it's the "nojavaScript" that needs to be removed.

Thanks!

try this:

document.getElementById("lines_list").className = ""; 

Here's a pure js solution:

var ulArr = document.getElementsByClassName('nojavaScript');
for (var i = 0; i < ulArr.length; i++) {
     ulArr[i].className = ulArr[i].className.replace('nojavaScript','');   
}

First you select all elements with the given class name, then iterate over the result and replace the given class in the className attribute with an empty string.

UPDATE:

Here's a more robust solution that turns the removal into a parameterized function and handles stripping extra whitespaces from the beginning, end, and middle of the className attribute.

function removeClass(elem, className) {
    //declare some regexes to help us strip the extra whitespace
    var trimLeft = /^\s+/,
        trimRight = /\s+$/,
        stripDouble = /\s+/g;
    //remove the class, strip extra whitespace, and reassign className
    elem.className = elem.className.replace(className, '').replace(trimLeft, '').replace(trimRight, '').replace(stripDouble, ' ');
}

//declare name of class to remove and get an array of elements with that class
var toRemove = 'nojavaScript',
    elArr = document.getElementsByClassName(toRemove);

//iterate over elements and remove the class
for (var i = 0; i < elArr.length; i++) {
    removeClass(elArr[i], toRemove);
}

Here's a live demo ->

function removeCSSClass(element, className) {
    var cssClass = ' ' + element.className + ' ';
    var index = cssClass.indexOf(' ' + className + ' ');
    if (index >= 0) {
        var newClass = cssClass.substr(0, index) + ' ' + cssClass.substr(index + className.length + 1);
        element.className = newClass;
    }
}

UPDATE : code now works in all occassions

Class name modification should be done on the className property with a RegExp replace to avoid clobbering other classNames which should stay:

var ele = document.getElementById( 'lines_list' );
ele.className = ele.className.replace( /(?:^|\s)nojavaScript(?:\s|$)/gm, ' ' );

http://jsfiddle.net/JAAulde/nWzaZ/3/

(genercized class names: http://jsfiddle.net/JAAulde/nWzaZ/2/ )

Without this regex, you either wipe the entire className, or you overkill and possibly take out a portion of foonojavaScript as well (you know, if you had such an odd class:P ). While this might not really be likely, it's good practice for when you run into code that might not be as specific.

This solution allows you to have as many classes on the element as you want, as similar as you desire, without worry of how you format them other than as specified by the W3C. No maintenance issues:).

(The RegExp specifically looks for your class preceded by start of string or white-space, and followed by white-space or end of string)

(This assumes you already have a handle on how to get the element(s) from the DOM in the first place.)

function removeClassFromElement(el,className){
    var classes = el.getAttribute('class').split(/[ ]+/g);
    var class = "";
    for(var i in classes)
        if(classes[i] != className)
            class += classes[i] + " ";
    el.setAttribute('class',class);

}
removeClassFromElement(document.getElementById('lines_list'),'nojavaScript');

Here's a non regex method that is considerate of multiple classes on an element.

function removeClass(element, cssClass) {

  var classes = element.className.split(' ');

  var j = classes.length;
  while (j--) {
    if (classes[j] === cssClass) {
      classes.splice(j, 1);
    }
  }

  element.className = classes.join(' ');
}   

var lines_list = document.getElementById('lines_list');
removeClass(lines_list, 'nojavaScript');

It splits on spaces to isolate whole class names whereas doing a simple search for the class name string and replacing with nothing might eat part of a longer class name.

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