Bardelman
Bardelman

Reputation: 2298

Applying jQuery methods on DOM elements

i started learning jQuery and i wish to know why jquery methods cannot be applied

in this example :

$('p')[0].html('salut !'); //for this instruction i got this error :
                           //"TypeError: $(...)[0].html is not a function "

while this one works :

$('body')[0].tagName.toLowerCase();

i m confused and i wish to know what is the difference between these 2 cases.

here is another example for the same problem :

var listItems = $( 'li' );
var rawListItem = listItems[0]; // or listItems.get( 0 )
var html = rawListItem.html();
// Object #<HTMLInputElement> has no method 'html'

here is the way on how to use jquery methods by using the .eq() :

var listItems = $( 'li' );
var secondListItem = listItems.eq( 1 );
secondListItem.remove();

thanks for supplying some explanation for this.

Upvotes: 1

Views: 122

Answers (2)

balexandre
balexandre

Reputation: 75073

It seams that you're learning by practicing, witch is a good thing, so here's some pointer:

  • jQuery uses objects, and when you wrap them into $(...) you will get an object
  • when you use an array pointer, like $('p')[0] you will always get what the native array outputs, witch is a string, and therefor, not an object

in order to retrieve the first element as an object, you have 3 choices

var jQueryObj = $('p:first'); // using :first

or

var jQueryObj = $("p").eq(0); // using eq()

or

var jQueryObj = $( $('p')[0] ); // wrap it in a jQuery call

and keep in mind, the console is always your best friend when testing javascript

enter image description here

Upvotes: 2

Matt
Matt

Reputation: 75317

A jQuery object is completely different to a DOMElement.

  • jQuery objects let you perform jQuery operations of them. html(), val(), eq(), etc.
  • DOMElement's... don't. As they're DOMElements, not jQuery objects.

If you check the documentation for .get(), you'll see you get a DOMElement back, not a jQuery object. The same goes for [0] etc.

eq(), however, returns a jQuery object which lets you do jQuery operations on them.

tagName is a DOMElement attribute, which is why can perform it on the DOMElements returned by get(), but can't perform it on the jQuery objects returned by eq(). The opposite applies for html() when used on get() and eq().

You can, of course, wrap any DOMElement in a jQuery object via $(), which'll let you perform jQuery operations on it;

$($('p')[0]).html('salut !');

But in your situations, you should be using eq():

$('p').eq(0).html('salut !');

Upvotes: 3

Related Questions