How do I access the list of classnames using javascript/jQuery?
here are the html elements :
<input class="myClass problemOne" type=text value=s开发者_Python百科omething></input>
<input class="myClass problemTwo" type=text value=somethingelse></input>
and here is the javascript and jquery in which I am tryign to access classaname, neither method a, or b works ... "classname is null or not an object".
var myElems = $(this).find(".myClass");
myElems.each(function(index) {
var classLista = $(this).className.split(/\s+/);
var classListb = myElems[index].className.split(/\s+/);
var classListc = this.className.split(/\s+/);
categories[index].key = classlist[1];
categories[index].value = $(this).value();
});
The end goal is to have problemOne and problemTwo returned as string and then stored in an array, which then go to the database blah blah blah.
Thanks a lot for any input !
edit explained end goal
You can use jQuery's .attr()
method to get any attribute, including classes.
$(this).find('.myClass').each(function(index) {
var element = $(this), classList;
classList = element.attr('class').split(/\s+/);
categories[index] = {
key : classList[1],
value : element.value()
}
});
Aside:
if categories[index]
already contains other info, you could use $.extend()
$.extend(categories[index], {
key : classList[1],
value : element.value()
});
The property is called className
. This is a property of a DOM element, not a jQuery element, so this.className
should work.
Just use the attr method and split:
<html>
<body>
<input class="myClass problem" type=text value=something></input>
<input class="myClass problem" type=text value=somethingelse></input>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
<script>
//<!--
$(document).ready(function(){
var Classes = $('input').attr('class').split(' ');
alert(Classes[0] + ' - '+ Classes[1]);
});
//-->
</script>
</body>
</html>
in POJ:
var elms = document.getElementsByTagName("INPUT"),
i = elms.length,
arr = [],
classArray;
while(i--) {
classArray = elms[i].className.split(/\s+/);
if (classArray.length > 1) {
arr.push(classArray[1]);
}
}
alert(arr.join(','));
精彩评论