Javascript add node - javascript

So I have a function like such:
var elem = document.createElement( 'svg' );
elem.id = 'svg1';
and I would like to, in a later function, be able to grab this element via document.getElementById('svg1').
I have found this does not work, and through some research, aka google, found that adding an element this way does not actually add it to the 'node tree'. How can I create an element so I can later reference the Id?

You need to add it to the DOM. For example, to add it as a child of an element with an ID "parent":
document.getElementById("parent").appendChild(elem);

To add an element to the DOM you do this:
document.body.appendChild(elem);
That adds the object to the BODY. If you want to add the node to another node, you replace body with getElementById("id").

Related

appendChild doesn't work when I'm trying to move span

I have a div in one place and I want to move it to another 2 places. I have id's for two parent tags and my spanEN to move. When I appendChild it only works for parentHeader.appendChild(spanEN );
var parentNav = document.getElementById('js-liveChatParentNav');
var parentHeader = document.getElementById('js-liveChatParentHeader');
var spanEN = document.getElementById("js-chat-sourceEN").childNodes[1];
parentNav.appendChild(spanEN );
parentHeader.appendChild(spanEN );
in console I see this: one appendChild works and the other one dosen't.
When you use appendChild to append an element that's already in the DOM, it's moved, not cloned. If you want to clone it, you can, via cloneNode:
parentNav.appendChild(spanEN);
parentHeader.appendChild(spanEN.cloneNode(true));
// ----------------------------^^^^^^^^^^^^^^^^
The true means "clone this node and its descendants."

jQuery insert child into element at set index

I would like to use jQuery to insert an html element inside another element and at a particular position.
I've found a way I can do it in Javascript but was wondering if there's a shorter 'one line of code' way of doing it in jQuery.
var container = document.getElementById("container");
container.insertBefore( html, container.children[0] );
Many thanks in advance
Use the selector for the n-th child of a given kind and the before method (assuming your new content comes in html) :
$("#container > div:nth-of-type(42)").before(html);
If you want to insert a new element as the first or last child of a container, there is another api option:
$("#container").append( html );
$("#container").prepend( html );
(For the sake of completeness, append / prepend are the links into the jQuery API docs)
If you want to add an element inside an other with jquery, you have to do like this :
$('#container').append(html);

Append child in DOM table

I am using clone to add new row to the DOM table dynamically from a button click event like below mentioned. but i want to append the cloned node to a specific row position in the DOM table. i know i can do that by using "insertrow" option but i want to use this using clone.
var newNode = tblBody.rows[1].cloneNode(true);
tblBody.appendChild(newNode);
is there any way to insert or append the "newNode" in a position i dynamically choose rather appending it as last row.
Use .insertBefore() from tblBody, and pass the newNode as teh first argument, and the child of tblBody before which the node should be inserted as the second argument.
// put this node----v before this----v
tblBody.insertBefore(newNode, tblBody.rows[i]);
If tblBody.rows[i] is null or undefined, then .insertBefore() will just behave like .appendChild(), and put it at the end.
node.insertBefore() is what you are looking for: https://developer.mozilla.org/en-US/docs/Web/API/Node.insertBefore

Remove an element from the DOM based on a variable reference to it?

I'm dynamically creating a div like this:
var gameScoreDiv= document.createElement('div');
gameScoreDiv.innerHTML= 'Score: 0';
wrapperDiv.appendChild(gameScoreDiv);
Later I need to remove this div from DOM. How can I get rid of that div?
Is it possible to simply delete the gameScoreDiv variable and have it remove also the DOM element (I have a feeling the answer is no)?
2019 update
You can remove node with ChildNode.remove() now:
gameScoreDiv.remove()
It's supported by every major browser with the not surprising exception of IE (for which you can add a tiny polyfill though, if needed).
You can do:
gameScoreDiv.parentNode.removeChild(gameScoreDiv);
or, if you still have reference to the wrapperDiv:
wrapperDiv.removeChild(gameScoreDiv);
In jQuery it would be:
$(gameScoreDiv).remove();
but this will use the parentNode way, see the source.
You're looking for the removeChild method.
In your case I see that wrapperDiv is the parent element, so simply call it on that:
wrapperDiv.removeChild(gameScoreDiv);
Alternatively, in another scope where that isn't available, use parentNode to find the parent:
gameScoreDiv.parentNode.removeChild(gameScoreDiv);
you can give your dynamically created div an id, and later you can see if any element with this id exists, delete it. i.e.
var gameScoreDiv= document.createElement('div');
gameScoreDiv.setAttribute("id","divGameScore");
gameScoreDiv.innerHTML= 'Score: 0';
wrapperDiv.appendChild(gameScoreDiv);
and later:
var gameScoreDiv= document.getElementById('divGameScore');
wrapperDiv.removeChild(gameScoreDiv);
You can try this:
gameScoreDiv.id = "someID";
//Remove the div like this:
var element = document.getElementById('someID');
element.parentNode.removeChild(element);

How to "create" HTML elements via Javascript?

Perhaps there's a better way to word my question by saying "Dynamically create DOM elements via Javascript", but I decided to write the simple title in case the latter was wrong. Anyway, is there a way I can "spawn" HTML elements via Javascript? For example, I can click a button on my site, and a paragraph will appear?
You can use createElement() like this:
var el = docment.createElement("elementtype");
This will create any element, if you replace elementtype with the type of element ("div", "p", etc.)
After that, you can use the native .appendChild() or .insertBefore() methods on whichever element you want to attach this new created element onto.
var attachTo = document.getElementById('appendToMe');
attachTo.appendChild(el);
And it'll be on the page after the last element inside of that element.
References:
https://developer.mozilla.org/en-US/docs/Web/API/document.createElement
https://developer.mozilla.org/en-US/docs/Web/API/Node.appendChild
https://developer.mozilla.org/en-US/docs/Web/API/Node.insertBefore
var element = document.createElement('p');
element.innerHTML = "Hey, this is a new paragraph!";
parentElement.appendChild(element);
For more information, refer to document.createElement and Node.appendChild

Categories

Resources