2

I am wondering how to inject HTML tags with DOM injection, without making use of the jquery library.

We want to generate several objects from an external javascript file, into the original page, but we don't want to be dependant on jquery (since it's 90kb) and we don't have control over the site which will use our script.

Erwin1441
  • 263
  • 1
  • 5
  • 19

3 Answers3

6

Either use

 object.innerHTML = "<br/><span>Text</span>"

Or use appendChild:

 var child = element.appendChild(child);

https://developer.mozilla.org/en-US/docs/DOM/Node.appendChild?redirectlocale=en-US&redirectslug=DOM%2Felement.appendChild

Both works.

JAR.JAR.beans
  • 9,668
  • 4
  • 45
  • 57
  • Using `innerHTML` isn't really good practize! Use `appendChild` every time (if possible)! See: http://stackoverflow.com/questions/2305654/innerhtml-vs-appendchildtxtnode – André Fiedler Nov 11 '13 at 15:56
3

Are you just looking for:

newNode = document.createElement(tagType);

and

parent.appendChild(newNode);

For more information about document level functions, see https://developer.mozilla.org/en-US/docs/DOM/document

For methods that manipulate elements, see https://developer.mozilla.org/en-US/docs/DOM/element

Alnitak
  • 334,560
  • 70
  • 407
  • 495
1

If you have many elements to create and they are contained in a common root node, I suggest to create a documentFragment and append into it all the nodes you need to generate through createElement() and appendChild() methods

Then just append the documentFragment into the document

From MDN reference: createDocumentFragment

Since the document fragment is in memory and not part of the main DOM tree, appending children to it does not cause page reflow (computation of element's position and geometry). Consequently, using document fragments often results in better performance

Fabrizio Calderan
  • 120,726
  • 26
  • 164
  • 177