March 29, 2012

first child in jquery

Question by Chapsterj

HTML:

        <div class="wrapper" style="display:none">
          <div class="panel"></div>
        </div>

JS CALL

var element = $(".wrapper");
element.toggle().children(":first").custom();
$(".wrapper .panel").custom();

CUSTOM JQUERY METHOD

  $.fn.custom = function() {  
        return this.each(function() {
           console.log(" this = ", this);
               // do something to each dom element.
        });
    };

Whats odd here is when I do a console.log in IE its showing the first call to the panel element as a

[object HTMLGenericElement]

but the second call shows it as a [objectHTMLDIVElement]

Why is this and how to have the first call be a [objectHTMLDIVElement]

Answer by Starx

You should use $(this) instead of this inside the each function.

return this.each(function() {
    console.log(" this = ", $(this));
    // do something to each dom element.
})

Besides, I checked this with chrome, safari, firefox and everywhere I am receiving the <div> element

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!