JQuery vs plain javascript: differences between append and appendChild when building a DOM tree

I asked a question about parsing a document for headers and creating a nested dom structure (via and unordered list)

how to properly analyze a document for any headings and build a <ul> tree of only those headings

The second answer suggested a solution with a violin: http://jsfiddle.net/fA4EW/

The solution is close, but does not seem to work for elements containing quotation properties, so I tried reorganizing it in jQuery http://jsfiddle.net/funkyeah/s8m2t/3/

I feel like I'm really close to getting it to work, but to deciding how

elm / li.appendChild and my $ elm / li.append codes (they seem to return different values ​​and modify the elm / $ elm object in different ways)

do { li = elm.lastChild; if(li == null) li = elm.appendChild(document.createElement("li")); elm = li.appendChild(document.createElement("ul")); cnt++; } while(cnt < (curLv - lv)); } li = elm.appendChild(document.createElement("li")); // replace the next line with archor tags or whatever you want li.innerHTML = node.innerHTML; 
+1
source share
1 answer

differences between append and appendChild

Ok, the jQuery variant is more reliable. It also takes several arguments like htmlString, a jQuery collection or element arrays, or even a callback function. And it automatically clones elements if they need to be inserted into multiple parents. the native method accepts only individual nodes (or individual DocumentFragments).

they seem to return different values

Yes. .append() returns the jQuery contextual collection (to which it is added), and .appendChild returns the added element.

This is apparently a problem in your code, a naive conversion will result in a different li value. If you need to bring the child back (there are simpler solutions), you can take a look at the .appendTo method.

and change the elm / $ elm object differently

No, they do not. Both place the added items at the end of the parent collection of children. You may have problems setting the innerHTML value of the return value that is not as expected (see above).

+2
source

Source: https://habr.com/ru/post/948236/


All Articles