Add an Element to the Dom with JavaScript

How to insert an element after another element in JavaScript without using a library?

referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);

Where referenceNode is the node you want to put newNode after. If referenceNode is the last child within its parent element, that's fine, because referenceNode.nextSibling will be null and insertBefore handles that case by adding to the end of the list.

So:

function insertAfter(referenceNode, newNode) {
referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}

You can test it using the following snippet:

function insertAfter(referenceNode, newNode) {
referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}

var el = document.createElement("span");
el.innerHTML = "test";
var div = document.getElementById("foo");
insertAfter(div, el);
<div id="foo">Hello</div>

Add array of elements to dom

The document.getElementsByClassName method returns an HTMLCollection-object, which is similar to an array, as in it has numeric keys which should be used.

e.g. for (var i = 0; i < myClass.length; ++i)

Once you use an incremental numeric index, you'll notice it actually behaves the same as your key in myClass, which is rather logical, as the key is the numeric index.

What is happening is that an HTMLCollection represents elements in document order (a so called live list, which reflects the changes in the DOM) and you are moving them around by appending them to the wrapper element (hence the order within the HTMLCollection changes too).

There are several tricks to work around this, the one closest to your current setup would be to walk through the HTMLCollection from end to start and insertBefore instead of appendChild

for (var len = myClass.length - 1; len >=0; --len) {
wrapper.insertBefore(myClass[len], wrapper.firstChild);
}

insertBefore fiddle

This works because the wrapper is (in your example) after the elements you're moving into it, therefor not changing the order of the elements.

There is another (easier) approach: document.querySelectorAll.
The querySelectorAll method returns a (static) NodeList, so you can safely assume the order will not change while you move nodes around.

The syntax is (IMHO) more convenient than getElementsByClassname, as it uses CSS Selectors (much like the popular javascript framework we won't mention)

querySelectorAll fiddle

Best way to add DOM Element to Body with JavaScript

The method appendChild take a node and add this node to the element on which it was called.

var node = document.createElement("DIV");  
var textNode = document.createTextNode("My Div content");
node.appendChild(textNode);
document.body.appendChild(node);

You can't use appendChild with a string containing the whole html.

What you can do is create a node. Set its innerHTML with the huge string. Then append the node to the body.


Code should be something similar to this:

var content = ....
var newNode = document.createElement("DIV");
newNode.innerHTML = content;
document.body.appendChild(newNode);

Add DOM elements to beginning of parent

I don't remember the exact syntax, but it something like:

var newDiv = document.createElement("div");
newDiv.innerHTML=xmlhttp.responseText;
document.getElementById("results").childNodes.addAt(0,newDiv);

if you can use jQuery, it's just simple as:

$("#results").prepend(xmlhttp.responseText);

Dynamically append the element through JavaScript Dom

The idea here is to create a container for all of the blocks and set the display style attribute of this container to flex, style.flewrap to wrap and you can control how many blocks you want per line using style.width attribute.

After creating this element you would want to append to it your dynamically created blocks like p2.appendchild(p1);
Here is the code :

let p2 = document.createElement('div');
p2.className= 'p2';
p2.style.display = 'flex';
p2.style.flexwrap = 'wrap';
p2.style.width = '800px'
for (i = 0; i <= 101; i++) {
...
for every document.body.append(p1); --> p2.append(p1);
...
}
document.body.appendChild(p2);

Adding a function into a DOM element

This will render a <p> element with the numbers 1 through 25 within it.

<html>
<body>

</body>
<script>
let p = document.createElement('p');
let script = document.createElement('script');
script.innerHTML = `
let numbers = "";
for (let e = 1; e <= 25; e++) numbers += e + " ";
document.currentScript.parentNode.innerHTML = numbers;
`
p.appendChild(script)
document.body.appendChild(p)
</script>

</html>

Appending already present element to DOM with Javascript/jQuery

Assuming I've understood you right, cloneNode may be what you are looking for.

You could clone your element and then append the clone to your parent node.

https://developer.mozilla.org/en/docs/Web/API/Node/cloneNode

Adding DOM Elements, what is the Right Way?

There is no "best" or "best practice". They are two different methods of adding content that have different characteristics. Which one you select depends upon your particular circumstance.

For creating lots and lots of elements, setting a block of HTML all at once has generally shown to be faster than creating and inserting lots of individual elements. Though if you really cared about this aspect of performance, you would need to test your particular circumstance in a tool like jsperf.

For creating elements with lots of fine control, setting classes from variables, setting content from variables, etc..., it is generally much easier to do this via createElement() where you have direct access to the properties of each element without having to construct a string.

If you really don't know the difference between the two methods and don't see any obvious reason to use one over the other in a particular circumstance, then use the one that's simpler and less code. That's what I do.

In answer to your specific questions:

  1. There is no "best" way. Select the method that works best for your circumstance.
  2. You will need to test the performance of your specific circumstance. Large amounts of HTML have been shown in some cases to be faster by setting one large string with .innerHTML rather than individually created an inserting all the objects.
  3. There is no "right way" or "best practice. See answer #1.
  4. There need be no difference in the end result created by the two methods if they are coded to create the same end result.

Insert array of elements into the DOM?

Iterating over array and appending each using appendChild:

itemsAll.forEach(el => {
document.body.appendChild(el)
})


Related Topics



Leave a reply



Submit