I am writing a simple accordion with just javascript.
I need to place an element before another element in the DOM. I know that I can do this with jQuery's insertBefore, but I am unfamiliar with how to do it using just JavaScript.
Any help is appreciated.
The native APIs have an .insertBefore method. You pass it the element you'd like to insert, and the element you want it inserted in front of.
// Create a new textNode, get reference to container
var foo = document.createTextNode("Foo"),
div = document.getElementById("foo");
// Insert new textNode before container's firstChild
div.insertBefore(foo, div.firstChild);
Fiddle: http://jsfiddle.net/jonathansampson/rn5pa/
Use insertBefore():
var el = document.getElementById('elementID'),
newElement = document.createElement('div');
el.parentNode.insertBefore(newElement, el);
Reference:
Node.insertBefore().
You can use insertBefore method
Related
I have a code already written in javascript:
var objTo = document.getElementById('krishna')
var href1 = document.createElement("div");
href1.setAttribute("style","float: left");
objTo.appendChild(href1);
Already so many elements are appended to href1 in javascript.
I want to add some more elements to href1 using jquery
I tried href1.append("<br>");
it says href1.append is not a function
How to use jquery append to append an element to href1.
You need to turn the native element into a jQuery object. Native elements don't recognize jQuery methods
Try
$(href1).append("<br>");
If you want to do all this with jQuery alone the code is quite simple
// create new <div> element and apply style
var href1 = $("<div>").css('float','left');
// append to id=krishna
$('#krishna').append(href1);
I have a website built in Expression Engine. In the back-end there is a code snippet that takes care of a JavaScript request and build a page based on the request.
I have a HTML Page without head tag.
This page is without styling
Sample:
<div class="top-arrow"><p><!--- Rest of code --></p>
</div>
<!-- Html page continues-->
I have added the following code in my attempt and it doesnt seem to work.
var span = document.createElement("span"); //Test element
span.textContent = "A <span> element.";
var node = document.getElementsByClassName("top-arrow");
node.insertBefore(span);
Below is what I get:
TypeError: node.insertBefore is not a function
node.insertBefore(span);
How best can I append text before the div with plain JavaScript.
getElementsByClassName will return array-like node-list which does not have method insertBefore
The Node.insertBefore(newNode, referenceNode) method inserts the specified node before the reference node as a child of the current node(If referenceNode is null, the newNode is inserted at the end of the list of child nodes)
Note: referenceNode is not an optional argument, if there is no ant ref node, pass null
Try this:
var span = document.createElement("span");
span.textContent = "A <span> element.";
var node = document.getElementsByClassName("top-arrow")[0];
//_____________________________________________________^^(Get the first element from collection)
node.insertBefore(span, null);
<div class="top-arrow">
<p>
</p>
</div>
document.getElementsByClassName("top-arrow") will return a live HTMLCollection. You can use it like an array:
node = document.getElementsByClassName("top-arrow")[0];
Also, if you want the new node to appear before top-arrow you need to do:
node.parentNode.insertBefore(span, node);
As it is node has no children, so there is no need to do insertBefore.
Even though your HTML code has no body and head, the browser will 'fix' your HTML and add one.
I would write your code like this:
var span = document.createElement("span"); //Test element
span.appendChild(document.createTextNode("A <span> element."));
var node = document.getElementsByClassName("top-arrow")[0];
node.parentNode.insertBefore(span, node);
Function getElementsByClassName() returns an array containing nodes with class specified. If you want to insertBefore or append anything to it you need to specify index of an element in this array. Also, insertBefore requires two arguments in function call (elementToInsert, elemenBeforeWhichYouWantToInsert). So, something like this should work:
document.getElementsByClassName('top-arrow')[0].insertBefore(element, beforeWhatToInsert);
Thank you guys for all your input they are very informative. I have solved this without the need of manipulating my DOM element by simply copying the dynamic part of the page and actually creating a new template in the back-end of Expression Engine and my problem was solved.
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);
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
I'm just wondering if the following is possible, lets say we have a dom element and we want to wrap this element in a div. So a div is inserted between the element and it's parent. Then the div becomes the element's new parent.
But to complicate things, elsewhere we have already done things like:
var testElement = document.getElementByID('testID')
where testID is a child of the element to be warapped in a div. So after we have done our insertion will testElement still be valid?
BTW: I'm not using jquery.
Any ideas?
Thanks,
AJ
You can use replaceChild [docs]:
// `element` is the element you want to wrap
var parent = element.parentNode;
var wrapper = document.createElement('div');
// set the wrapper as child (instead of the element)
parent.replaceChild(wrapper, element);
// set element as child of wrapper
wrapper.appendChild(element);
As long as you are not using innerHTML (which destroys and creates elements), references to existing DOM elements are not changed.
Assuming you are doing your manipulation using standard DOM methods (and not innerHTML) then — yes.
Moving elements about does not break direct references to them.
(If you were using innerHTML, then you would be destroying the contents of the element you were setting that property on and then creating new content)
You probably want something like:
var oldParent = document.getElementById('foo');
var oldChild = document.getElementById('bar');
var wrapper = document.createElement('div');
oldParent.appendChild(wrapper);
wrapper.appendChild(oldChild);
In pure JS you can try something like this...
var wrapper = document.createElement('div');
var myDiv = document.getElementById('myDiv');
wrapper.appendChild(myDiv.cloneNode(true));
myDiv.parentNode.replaceChild(wrapper, myDiv);
Here is another example, only the new element wraps around 'all' of its child elements.
You can change this as necessary to have it wrap at different ranges. There isn't a lot of commentary on this specific topic, so hopefully it will be of help to everyone!
var newChildNodes = document.body.childNodes;
var newElement = document.createElement('div');
newElement.className = 'green_gradient';
newElement.id = 'content';
for (var i = 0; i < newChildNodes.length;i++) {
newElement.appendChild(newChildNodes.item(i));
newChildNodes.item(0).parentNode.insertBefore(newElement, newChildNodes.item(i));
}
You will want to modify the 'document.body' part of the newChildNodes variable to be whatever the parent of your new element will be. In this example, I chose to insert a wrapper div. You will also want to update the element type, and the id and className values.