Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use .get(0) or .html() to return HTML with jQuery

So as far as I can tell, if I have

<div id="thing">OMG there's awesome stuff in here</div>

and need to plant that html somewhere else, I have the option of using:
$('#thing').html(); or $('#thing').get(0);

Is there a greater internet standard in using one or the other? They do the exact same thing, right?

Thanks for the help!

like image 583
OldDrunkenSailor Avatar asked Nov 17 '11 00:11

OldDrunkenSailor


People also ask

What is the jQuery method for retrieving the HTML content of an element?

jQuery html() Method The html() method sets or returns the content (innerHTML) of the selected elements. When this method is used to return content, it returns the content of the FIRST matched element.

How HTML elements are used in jQuery with example?

What is the use of html() method in jQuery ? The html() method in jQuery is used to get the contents of the first element in the set of matched elements or is used to set the HTML contents of every matched element. It returns the content of the first matched element. This function does not accept any arguments.

What does $() do in jQuery?

When a jQuery object is passed to the $() function, a clone of the object is created. This new jQuery object references the same DOM elements as the initial one.

Which methods return the element as a jQuery object?

jQuery also has a method named . get() which provides a related function. Instead of returning a jQuery-wrapped DOM element, it returns the DOM element itself.


2 Answers

They do the exact same thing, right?

Wrong. The html method returns the contents of the selected element, as a string. The get method returns the element itself, as an object. For example, we have this element:

<div id="example">
    <span>A child element</span>
</div>

The methods would return the following:

console.log($("#example").html()); //Prints "<span>A child element</span>"
console.log($("#example").get(0)); //Prints an object

You can try that for yourself here.

like image 118
James Allardice Avatar answered Sep 29 '22 04:09

James Allardice


.get(0) will give you the first element in the jquery object, not the HTML within that. You would then need to get the html. If you're using jquery, use jquery. I see no reason not to use .html().

like image 23
James Montagne Avatar answered Sep 29 '22 03:09

James Montagne