简体   繁体   English

使用 JavaScript 从 HTML 元素中删除 class

[英]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.我正在尝试使用 JavaScript 从 html 标签中删除 class 但我不知道从哪里开始。 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.虽然我在 jQuery 中相当流利,但我不在 JavaScript 中,我需要在这种情况下使用 JavaScript 到目前为止我发现自己使用的任何东西都不需要调整。 Hopefully someone can explain it in a fool-proof way.希望有人能以一种万无一失的方式解释它。

The element the class is attached to is the "ul" tag. class 附加到的元素是“ul”标签。 The class is named "nojavaScript" and is only applied to this single instance of the "ul" tag. class 被命名为“nojavaScript”并且只应用于“ul”标签的这个单一实例。 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.正如我所说,class 在页面中只使用一次,“ul”标签用于具有不同类或 id 的其他实例。 If it would make it easier for the JavaScript, I can change the class to an id.如果它能让 JavaScript 更容易,我可以将 class 更改为 id。

I hope I have given you enough to go on.我希望我已经给你足够的go了。 I will include an example of the html code below.我将在下面包含 html 代码的示例。

<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.正如我提到的,如果删除 id 比删除 class 更容易,我可以将当前 id 设为 class,并将当前 class 设为 id。 But essentially it's the "nojavaScript" that needs to be removed.但本质上是需要删除的“nojavaScript”。

Thanks!谢谢!

try this:尝试这个:

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

Here's a pure js solution:这是一个纯js解决方案:

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.首先你 select 具有给定 class 名称的所有元素,然后迭代结果并用空字符串替换className属性中给定的 class 。

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 并处理从className属性的开头、结尾和中间剥离额外的空格。

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: Class 名称修改应该在className属性上使用 RegExp 替换来完成,以避免破坏其他应该保留的 className:

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

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

(genercized class names: http://jsfiddle.net/JAAulde/nWzaZ/2/ ) (通用 class 名称: 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 ).如果没有这个正则表达式,您要么擦除整个类名,要么过度杀伤并可能删除foonojavaScript的一部分(你知道,如果你有这样一个奇怪的 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.此解决方案允许您在元素上拥有尽可能多的类,与您希望的相似,而不用担心您如何格式化它们,而不是 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) (正则表达式专门查找您的 class 前面是字符串或空格的开头,然后是空格或字符串的结尾)

(This assumes you already have a handle on how to get the element(s) from the DOM in the first place.) (这假设您首先已经掌握了如何从 DOM 中获取元素的方法。)

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.它在空格上拆分以隔离整个 class 名称,而对 class 名称字符串进行简单搜索并用空替换可能会占用更长的 class 名称的一部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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