Reputation: 14684
How can I get a #<HTMLDivElement>
as a jQuery object?
I need to do the following: I have a list of div's with the class contents. So I iterate over it until I find the one with the additional class: "test"
here is my code:
$.each( $(".contents"), function( key, value ) {
if (value.hasClass("test"))
{
alert("got it");
}
});
I'm getting the exception: Uncaught TypeError: Object #<HTMLDivElement> has no method 'hasClass'
Upvotes: 4
Views: 16520
Reputation: 148150
The each()
function gives you DOM
object and you have to convert it to jQuery
object. You can pass value
to $
jQuery function to convert it to jQuery object.
$.each( $(".contents"), function( key, value ) {
if ($(value).hasClass("test"))
{
alert("got it");
}
});
You do not need to iterate through each and simplify it like
elements = $(".contents.text")
Upvotes: 10
Reputation: 145408
Why not to do it simpler with:
$(".contents.test"). ...
Here jQuery will select element that has both "contents"
and "test"
classes set.
DEMO: http://jsfiddle.net/xfErG/
Upvotes: 2
Reputation: 943686
The main jQuery function can accept a DOM Element as its argument.
var foo = jQuery(HTMLElementNode);
The following two lines of code have the same end result:
var foo = jQuery('#foo');
var foo = jQuery(document.getElementById('foo'));
Upvotes: 0