admin管理员组文章数量:1314480
I have a bunch of inputs like this
<input id="someId" type="button" class="SomeClass" onclick="determineClass(this.id, event)" />
From javascript I would like to get the class, it's different for each input.
function determineClass(id, e) {
var elementClass = //Somehow get the class here
}
It can be using jQuery or just plain javascript... Does anyone know how to do this?
Thanks, Matt
I have a bunch of inputs like this
<input id="someId" type="button" class="SomeClass" onclick="determineClass(this.id, event)" />
From javascript I would like to get the class, it's different for each input.
function determineClass(id, e) {
var elementClass = //Somehow get the class here
}
It can be using jQuery or just plain javascript... Does anyone know how to do this?
Thanks, Matt
Share Improve this question asked Sep 15, 2009 at 0:45 MattMatt 5,60524 gold badges84 silver badges122 bronze badges5 Answers
Reset to default 6alert($('#someId').attr('class'));
If your input has multiple classes, attr('class')
returns a space-delimited list of classnames. You can get the last one as follows:
alert($('#someId').attr('class').split(' ').slice(-1));
See Attributes/attr
You would use:
$('#someId').attr('class')
But beware that if it has multiple classes it will return a string of all of them, so you'll have to use indexOf or a regex to check for a specific class in that case.
A bit simpler using plain ol' JavaScript:
function determineClass(id, e)
{
var elem = document.getElementById(id);
if(elem)
{
alert(elem.className);
}
}
Using plain ol' javascript, if you already have a variable/reference to the element, you can pull the class out using "element.className"
So, for your element "someId" above:
element = document.getElementById('someId');
if(element) elementClass = element.className
This gets a little more plicated if you have multiple classes assigned to the element -- you'd have to split what you find in the className property by a space in order to separate them -- but that's the basics.
That said, if you've got the chance, use jQuery. It generally makes this kind of thing easier.
[edit]
Ah crap... not what you meant...
$('#id').attr('class');
[/edit]
本文标签: How can I retrieve the class of an element using jQueryjavascriptStack Overflow
版权声明:本文标题:How can I retrieve the class of an element using jQueryjavascript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741968584a2407695.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论