How to get the class names using jquery?
Hey, I'm wondering how I can get the class names dynamically using jquery for the script below.
The HTML output looks like this:
<div id="main-info-1" class="maini">
<p>this is a paragraph.</p>
</div>
So, I'm trying to get the class name dynamically instead of hard coded like it is above.
There are two parts where I need to get the class names in the jquery script:
1.) pc.children('div.maini').remove();
2.) maini_s = $('div.maini').remove();
As you can see the class 'maini' is hard coded and im unsure how to get the class name dynamically and put it properly in the script.
The jQuery file:
<script type="text/javascript">
// make them global to access them from the console and use them
// in handlePaginationClick
var maini_s;开发者_JAVA技巧
var num_of_arts;
var ipp;
function handlePaginationClick(new_page_index, pagination_container) {
var pc = $(pagination_container);
pc.children('div.maini').remove();
for(var i=new_page_index*ipp; i < (new_page_index+1)*ipp ;i++) {
if (i < num_of_arts) {
pc.append(maini_s[i]);
}
}
return false;
}
$(document).ready(function() {
maini_s = $('div.maini').remove();
num_of_arts = maini_s.length;
ipp = 3;
// First Parameter: number of items
// Second Parameter: options object
$("#News-Pagination").pagination(6, {
items_per_page:ipp,
callback:handlePaginationClick
});
});
</script>
Any help on this would be awesome, thank you.
It depends on what you're after exactly.
You can get the class names using jQuery or plain javascript:
// jQuery
$myElement.attr('class');
// javascript
myElement.className
This will give you the string value of the class
attribute of the element. If the element has more than one class (eg: <div class="foo bar">
) the above methods will return "foo bar"
. If you want an array of classes on an element, then you just need to split the result on whitespace:
var classes = myElement.className.split(/\s+/);
// classes = ["foo", "bar"]
Using jQuery to get that class name works like this:
$('#main-info-1').attr('class');
You can detect, add and remove classes without having to worry about splitting on whitespace when using multiple classes. And there's a convenient toggle too:
// toggle example
$('ele').toggleClass('active');
// toggle with optional bool parameter
$('ele').toggleClass('active', isActive );
// detect/add/remove classes without having to split on blank space " "
if ($('ele').hasClass('dull'))
$('ele').removeClass('dull').removeClass('productive');
else
$('ele').addClass('fun').addClass('profitable');
精彩评论