Reputation: 2298
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
Reputation: 75073
It seams that you're learning by practicing, witch is a good thing, so here's some pointer:
$(...)
you will get an object$('p')[0]
you will always get what the native array outputs, witch is a string, and therefor, not an objectin 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
Upvotes: 2
Reputation: 75317
A jQuery object is completely different to a DOMElement
.
html()
, val()
, eq()
, etc.DOMElement
's... don't. As they're DOMElement
s, 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 DOMElement
s 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