document.getElementById("MyElement").className =document.getElementById("MyElement").className.replace( /(?:^|\s)MyClass(?!\S)/g , '' )/* Code wrapped for readability - above is all one statement */
这个regex的解释如下:
(?:^|\s) # Match the start of the string or any single whitespace character
MyClass # The literal text for the classname to remove
(?!\S) # Negative lookahead to verify the above is the whole classname# Ensures there is no non-space character following# (i.e. must be the end of the string or space)
g标志告诉替换根据需要重复,以防类名已添加多次。
要检查一个类是否已经应用于一个元素:
上面用于删除类的相同regex也可以用作检查特定类是否存在:
if ( document.getElementById("MyElement").className.match(/(?:^|\s)MyClass(?!\S)/) )
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.LoadIf Not Page.IsPostBack ThenlbSave.Attributes.Add("onmouseover", "this.className = 'LinkButtonStyle1'")lbSave.Attributes.Add("onmouseout", "this.className = 'LinkButtonStyle'")lbCancel.Attributes.Add("onmouseover", "this.className = 'LinkButtonStyle1'")lbCancel.Attributes.Add("onmouseout", "this.className = 'LinkButtonStyle'")End IfEnd Sub
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');}
<div class="foo bar" id="container">"Sed ut perspiciatis unde omnisiste natus error sit voluptatem accusantium doloremque laudantium,totam rem aperiam, eaque ipsa quae ab illo inventore veritatis etquasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsamvoluptatem quia voluptas</div>
<button onclick="addClass()">AddClass</button>
<button onclick="replaceClass()">ReplaceClass</button>
<button onclick="removeClass()">removeClass</button>
// Get the Elementconst el = document.querySelector('#element');
// Add CSS propertyel.style.margintop = "0px"el.style.margintop = "25px" // This would add a 25px to the top of the element.
<!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>
function removeClass() {
let element = document.getElementById('id1');
// removing class
element.className = '';
}
Case 2 : 删除多个类
如果元素有多个类,则首先使用 className属性从元素中获取所有类,然后使用替换方法并用空字符串替换所需的类,最后将其分配给元素]的 className属性。
function removeClass() {
let element = document.getElementById('id1');
// removing class
element.className = element.className.replace('class1', '');
}
function checkClass() {
let element = document.getElementById('id1');
// checking class
if(element.classList.contains('beautify') {
alert('Yes! class exists');
}
}
4. 切换课堂
使用 classList.toggle()方法切换类。
function toggleClass() {
let element = document.getElementById('id1');
// toggle class
element.classList.toggle('beautify');
}
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);