1

I know it is a stupid question but i just dont get it. To get the whole element of div1 why we use this :

var html = $("<div />").append($("#div1").clone()).html();

instead of just:

var html = $("#div1").clone();

or even:

var html = $("#div1");

It totally work! Why? And it also perfect for drag and drop (the last one) since it doesnt create a copy like the first and second. Thank you very much for help! I'm just a beginner.

Best_Name
  • 149
  • 2
  • 13
  • Who's using that? The first example makes no sense at all? Sometimes though, making a clone and inserting it into an empty parent can be useful, just not in the case where you only need the HTML as a string, then `$('#div1').get(0).outerHTML` is a lot easier. – adeneo Jul 15 '17 at 07:26
  • @adeneo i found it here https://stackoverflow.com/questions/3614212/jquery-get-html-of-a-whole-element – Best_Name Jul 15 '17 at 07:31
  • Well, that's not a very good answer. If the aim is to *only* get the HTML as a string, neither cloning the element nor insterting it in an empty parent is neccessary. – adeneo Jul 15 '17 at 07:36

1 Answers1

3

Ideally you'd want to work with the HTML instead of manipulating it with JavaScript or jQuery.

The reasons being:

  1. JavaScript is going to take time to process the script.
  2. Having additional JS code, which isn't adding any value will lead to a maintenance nightmare down the road.

jQuery is a library, which gives us short-cuts for working with native/vanilla JavaScript. Here is what each of those 2 functions are doing.

.clone()

Create a deep copy of the set of matched elements.

.append()

Insert content, specified by the parameter, to the end of each element in the set of matched elements.

$("#div1") is the same as JavaScript's document.getElementById() method / function.

From the Mozilla Developer Network:

Returns a reference to the element by its ID; the ID is a string which can be used to uniquely identify the element, found in the HTML id attribute.

If you don't need to make jQuery chains...

var html = $("<div />").append($("#div1").clone()).html(); 

... you'll look like a smarter web developer to other web developers who may code review your work, if you work with the HTML like this...

<div id="div1"></div>
<div id="div2" class="blink"></div>

... and jQuery, like this:

let obj1 = $("#div1");
let obj2 = $("#div2");

// Do something with obj1 & obj2 or the HTML for both DOM nodes.

obj1.html('Hello');
obj2.html('World');
obj1.addClass('red');
obj2.removeClass('blink');

Then you should get:

<div id="div1" class="red">Hello</div>
<div id="div2">World</div>

Tip: Don't write extraneous code simply to obfuscate it. You'll have a hard time reading it later on. Smaller code is good code! It looks professional.

Keep on learning!

Clomp
  • 3,168
  • 2
  • 23
  • 36