I have a jQuery element but I have to send it to a function that only accepts HTML elements. How can I convert the jQuery element to an HTML element?
2 Answers
Try myJQueryElement.get(0) or myJQueryElement[0]. (get() is most useful when you need negative indices, for example, as described in the documentation for get().)
3 Comments
Francois
warning: get(0) will not return the inner elements
Aakash
>
negative index - A negative index is counted from the end of the matched set, so this example returns the last item in the list. For ex.$('div').get(0); will return the last div element.GIA
briefly,
$("# foo").get(0) does the same as $("# foo")[0] but $("# foo").get(0) is slower.$("#foo")[0] will get you an HTML element. Using brackets is a tiny bit faster than using .get() but not something you'll likely notice unless you are doing it millions of times.
5 Comments
Michael Lorton
And not even then! If you run it 10 million times, brackets will take 150 seconds, get will take 170 seconds. I bet you cannot notice without sitting there counting "1-Mississippi, 2-Mississippi..." Mississippilessly, it's impossible to tell the difference. Do whichever way you feel is more readable. (BTW, I'm only posting this comment because it gives me the change to use the word "Mississippilessly" in a sentence. If anyone wants to discuss the future of the Anglican Church with me, I'm dying to use "antidisestablishmentarianistically".)
Dennis
It's ironic that you espoused readability right after using
Mississippilessly but you're right. get lets you either convert the jQuery object to an array of DOM objects by calling it without arguments, or get the _n_th from the end by providing a negative argument. Otherwise it's just a function that uses the brackets.void
omg. this issue has taken literally days from me. thanks for this answer !
Denis G. Labrecque
@Malvolio Shouldn't that word just be "establishmentarianistically", since (anti-) and (dis-) are two nots that cancel?
Michael Lorton
@DenisG.Labrecque — establishmentarianism is the belief you should establish a state church in a country that lacks one; antidisestablishmentarianism is the belief you should continue the state church in a country that already has it. So far as I can tell, establishmentarianism is quite rare — almost no one wants to start a state church. Antidisestablishmentarianism is a common conservative position: "We have always had this nonsense, so we always should."