如何在javascript中删除该类? [英] How to remove the class in javascript?
问题描述
<div id="tab1" class="nav left">
<ul>
<li><a href="/magento/" class="now">Home</a></li>
......
</ul>
</div>
现在,我想删除 class =now
或将类值设置为空。如果url不在mangento上,我使用以下代码。但是我不知道如何写最后一部分。
Now, i want to remove the class="now"
or set the class value empty. If the url not on mangento, I using the following code. But the I don't know how to write the last part.
window.onload = function removeNow() {
var div = document.getElementById("tab1").getElementsByTagName("a");
if (window.location.pathname != '/magento/') {
div.removeClass();
}
}
谢谢。
推荐答案
在现代浏览器中,您可以使用 classList
API:
In modern browsers you can use the classList
API:
div.classList.remove( 'now' );
但是您的代码特有的问题:您必须循环才能删除该类。所以尝试这样:
But a problem specific to your code: You must loop in order to remove the class. So try this:
for ( var i = 0; i < div.length; i++ ) {
div[i].classList.remove( 'now' );
}
如果您的浏览器不支持 classList
,使用这个 removeClass
shim:
If your browser doesn't support classList
, use this removeClass
shim:
function removeClass( elem, name ) {
var classlist = elem.className.split( /\s/ ),
newlist = [],
idx = 0;
for ( ; idx < classlist.length; idx++ ) {
if ( classlist[ idx ] !== name ) {
newlist.push( classlist[ idx ] );
}
}
elem.className = newlist.join(" ");
return true;
}
或与 jQuery (我们不需要使用 classList
或 className
):每个(function(){
if(window.location)$($)
or with jQuery (with which we are not required to use classList
or className
):
$('a').each(function() {
if (window.location.pathname != '/magento/')
$(this).removeClass();
});
这篇关于如何在javascript中删除该类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!