OMG there awesome stuff in here...">

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

So, as far as I can tell, if I have

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

and I need to install this html in another place, I have the opportunity to use:
$('#thing').html(); or $('#thing').get(0);

Is there a higher internet standard when using one or the other? They do the same thing, right?

Thanks for the help!

+7
source share
8 answers

They do the 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> 

Methods will return the following:

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

You can try it for yourself here .

+14
source

.get(0) will provide you with the first element in the jquery object, not the HTML inside it. Then you will need to get html. If you are using jquery, use jquery. I see no reason not to use .html() .

+7
source

If you want to duplicate some elements, do not use html . This is a very inefficient way to clone elements. There is a much better way called clone (oddly enough):

 $('#thing').clone(true).removeProp('id').appendTo('#someOtherElement'); 

Note that I am removing the id property, as it must be unique.

+2
source

These two things are close to the same thing (pay attention to adding .innerHTML to what you had in your question):

 $('#thing').html(); $('#thing').get(0).innerHTML; 

The first creates a jQuery object, then calls the .html () method on it (which takes the HTML from the .innerHTML property in .innerHTML ).

The second creates a jQuery object, and then extracts the first DOM element from it and gets the innerHTML property from it.

In general, if you already have a jQuery object, use .html() . If you already have a DOM object, use .innerHTML .

+2
source

I used only .html () and I work in a firm. I have never seen .get (0) used for something like this

0
source

They are quite different. The get method returns a DOM element, and html() returns a string. Here, it looks like you want HTML, so use html()

0
source

These two methods are different from each other.

get() Get the DOM elements consistent with the jQuery object. See: http://api.jquery.com/get/

html() Get the HTML content of the first element in the set of matched elements. See: http://api.jquery.com/html/

0
source

No, they do not do the same.

.html() returns an HTML string representing the DOM structure inside the element contained in the jQuery collection object: "OMG is awesome stuff there."

.get(0) returns the first DOM object object from the collection, in this case a DOM node such as a DIV tag with the identifier "thing" and the child text node with the value "OMG is awesome stuff here"

0
source

All Articles