What's the difference between .clone() and .html()?

前端 未结 5 592
广开言路
广开言路 2021-02-05 15:03

What is the difference between Jquery\'s .clone() and .html() functions?

Jquery documentation states:

The .clone() method performs a deep copy of

5条回答
  •  不知归路
    2021-02-05 15:44

    .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.

提交回复
热议问题