What is the difference between Jquery's .clone() and .html() functions?
Jquery documentation states:
The .clone() method performs a deep copy of the set of matched elements, meaning that it copies the matched elements as well as all of their descendant elements and text nodes.
In an HTML document, .html() can be used to get the contents of any element. If the selector expression matches more than one element, only the first match will have its HTML content returned.
To me these seem to interchangeable, so are there specific situation where one would be used of the other?
The clone() method makes a copy of selected elements, including child nodes, text and attributes.
clone - create something new based on something that exists. copying - copy from something that exists to something else (that also already exists).
Cloning. Cloning in javascript is nothing but copying an object properties to another object so as to avoid creation of an object that already exists. There are a few ways to clone a javascript object. 1) Iterating through each property and copy them to a new object.
The clone() is an inbuilt method in jQuery which is used to make a copy of selected elements including its child nodes, text and attributes. Syntax: $(selector).clone(true|false) Parameter: It accepts an optional parameter which could be either true or false specifies that event handler should be copied or not.
.clone()
returns a jQuery object while .html()
returns a string.
Use .clone()
if you want a copy of the jQuery objects and use .html()
to get the inner HTML of a jQuery object in a string format. Each method has its own purpose (and cost).
Also, as sgroves pointed out, ".clone()
performs a deep copy of the set of elements found by the selector, while .html()
only [uses] the first matched element."*
*Although note that .html(newContent)
will set the inner HTML of a set of matched elements. Fiddle
Another note: the (generally) "faster" option is to use strings rather than jQuery objects when doing DOM manipulation (JSPerf). Thus, I'd recommend .html()
if all you need is text content. Again though: each method has its own purpose.
Here are a list of differences :
.clone
can be used on multiple selected elements while .html()
returns only the html of the first element.
.clone
returns a jQuery object while .html
returns a string.
.clone
can (if specified) keep any event and data of the DOM element. .html
will not.
.clone
makes a copy of the selected element and all its descendents while .html
only gets its descendents. In other words, comparing to DOM methods, .clone
is similar to .outerHTML and .html
is more like .innerHTML.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With