最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Object #<HTMLDivElement> as jQuery object - Stack Overflow

programmeradmin4浏览0评论

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'

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'

Share Improve this question asked May 6, 2013 at 9:47 gurehbguigurehbgui 14.7k33 gold badges111 silver badges190 bronze badges 2
  • 1 Just pass it to the jQuery constructor. – Bergi Commented May 6, 2013 at 9:50
  • Why don't you use some selector like $(".contents.test").each(alert.bind(window, "got it"))? Or $(".contents").filter(".test")? – Bergi Commented May 6, 2013 at 9:51
Add a ment  | 

3 Answers 3

Reset to default 10

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")

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/xfErG/

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'));
发布评论

评论列表(0)

  1. 暂无评论