funkyeah
funkyeah

Reputation: 3174

jQuery vs. plain javascript: differences between append and appendChild when building DOM tree

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

how to robustly parse a document for any headings and build a <ul> tree of just those headings

In the second answer a solution was proposed along with a fiddle: http://jsfiddle.net/fA4EW/

The solution is close but doesn't seem to work for elements containing properties with quotes, so I tried to refactor it in jQuery http://jsfiddle.net/funkyeah/s8m2t/3/

I feel like I am really close to making it work but the resolving the different between how

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

      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;

Upvotes: 1

Views: 1784

Answers (1)

Bergi
Bergi

Reputation: 664434

differences between append and appendChild

Well, the jQuery variant is more robust. It also takes multiple arguments, of type htmlString, jQuery collection or Arrays of elements, or even a callback function. And it automatically clones the elements if they are to be inserted into multiple parents. The native method only takes single nodes (or single DocumentFragments).

they seem to return different values

Yes. .append() returns the context jQuery collection (to which it appends), while .appendChild returns the appended element.

This seems to be the problem in your code, a naive transformation would lead to a different li value. If you do need to get the child back (there are simpler solutions), you might have a look at the .appendTo method.

and modify the elm/$elm object differently

No, they don't. Both put the appended elements to the end of the parent's children collection. You might have problems with setting the innerHTML value of the return value which is not what you expected (see above).

Upvotes: 2

Related Questions