I set the class of an element, and now I want to change the class of the element through JavaScript. I tried jQuery's attr to modify the class attribute, but it didn't work.
html:
<nav>
<ul class="pager" id="pageCtr">
<li class="previous" id="prevBTN">
<a href="#" onclick="prevPage()"><span>←</span>前一页</a>
</li>
</ul>
</nav>
js:
$('#prevBTN').className='previous disabled';
Hypothetical elements
You can change it like this
Tried and tested.
jQuery just
document.getElementById('idValue')
改成$('#idValue')
and it’s readyHTML:
JS:
not pass
attr
,而是通过className
PS:
If you want to add the attribute
disabled
toli
, you can do this, instead of addingclass
butattr
:li
添加属性disabled
可以这样做,不是添加class
而是attr
:$('#prevBTN').attr('disabled', true);
$('#prevBTN').attr('disabled', true);
Remove attr:
What is the code of the original poster?
Why is it okay for me to directly use attr() to set the class?
In addition, jQuery also has two methods: addClass() and removeClass. I generally use these two methods to operate classes.
jQuery has special methods for operating classes, you can check the relevant API
Thanks to @daryl and @tony_yin for their enthusiastic answers. I want to use it myself
<li>
标签里面的<a>
换成<button>
,能实现禁用按钮效果,但是.pager
的 BootStrap 默认样式会变化;将
<li class="previous" id='prevBTN'>
换成<li class="previous disabled" id='prevBTN'>
使用document.getElementById('prevBTN').className='previous disabled';
确实可行,但使用 jQuery 时会出现问题,$('prevBTN').className='previous disabled';
就不能实现,主要原因是$('prevBTN')
并不能得到 DOM 元素,而 className 是 DOM 里面的属性,$(selector)
I can only get a collection of DOM elements that meet the selector conditions,Solution:
$('prevBTN').get(0).className='previous disabled';