So, if I have HTML like this:
<div id='div'>
<a>Link</a>
<span>text</span>
</div>
How can I use JavaScript to add an HTML element where that blank line is?
node = document.getElementById('YourID');
node.insertAdjacentHTML('afterend', '<div>Sample Div</div>');
Available Options
beforebegin, afterbegin, beforeend, afterend
As you didn't mention any use of javascript libraries (like jquery, dojo), here's something Pure javascript.
var txt = document.createTextNode(" This text was added to the DIV.");
var parent = document.getElementById('div');
parent.insertBefore(txt, parent.lastChild);
or
var link = document.createElement('a');
link.setAttribute('href', 'mypage.htm');
var parent = document.getElementById('div');
parent.insertAfter(link, parent.firstChild);
Instead of dealing with the <div>'s children, like other answers, if you know you always want to insert after the <a> element, give it an ID, and then you can insert relative to its siblings:
<div id="div">
<a id="div_link">Link</a>
<span>text</span>
</div>
And then insert your new element directly after that element:
var el = document.createElement(element_type); // where element_type is the tag name you want to insert
// ... set element properties as necessary
var div = document.getElementById('div');
var div_link = document.getElementById('div_link');
var next_sib = div_link.nextSibling;
if (next_sib)
{
// if the div_link has another element following it within the link, insert
// before that following element
div.insertBefore(el, next_sib);
}
else
{
// otherwise, the link is the last element in your div,
// so just append to the end of the div
div.appendChild(el);
}
This will allow you to always guarantee your new element follows the link.
If you want to use something like jQuery you can do something like this:
$('#div a').after("Your html element");
jQuery has a nice, built in function for this: after(), at http://api.jquery.com/after/
In your case, you will probably want a selector like this:
$('#div a').after('<p>html element to add</p>');
The code examples from the link given above also show how to load jQuery if that is new to you.
Element#after can be used to insert elements directly after a certain HTML element.
For example:
document.querySelector("#div > a").after(
Object.assign(document.createElement('div'), {textContent: 'test', style: 'border: 1px solid'}));
<div id='div'>
<a>Link</a>
<span>text</span>
</div>
Assuming that you are only adding one element:
document.getElementById("div").insertBefore({Element}, document.getElementById("div").children[2]);
Related
i was wondering if there's a jquery (or some other library) function that allows me to insert a node (div) between two other nodes (divs) based on its attribute.
For example:
Lets say i have this html code:
<div value=111/>
<div value=222/>
<div value=444/>
i want to insert <div value=333/> between the 222 and 444 accordingly.
Thanks to all helpers.
Yes you can do this.
obtain desired div using querySelector
use after method to add new element after the one obtained in the previous step
const div = document.createElement('div');
div.textContent = 'three';
const target = document.querySelector('div[value=two]');
target.after(div);
<div value="one">one</div>
<div value="two">two</div>
<div value="three">four</div>
To dynamically the find correct spot, you can use find method like this.
find the first element with value bigger than the one you provide
use before method to place the new element before the one from the previous step
const myValue = 333;
const div = document.createElement('div');
div.textContent = myValue;
const target = [...document.querySelectorAll('div')]
.find(v => Number(v.getAttribute('value')) > myValue );
target.before(div);
<div value="111">111</div>
<div value="222">222</div>
<div value="444">444</div>
use after();
here is working example in codepen
https://codepen.io/anon/pen/BVjbqZ
Both jQuery offers a variety of methods for this: insertBefore, insertAfter, before, and after.
The DOM provides insertBefore and insertAdjacentHTML.
For instance, using jQuery's before:
$("div[value=444]").before("<div value=333></div>");
Or using the DOM's insertBefore:
var div = document.createElement("div");
div.setAttribute("value", "333");
var target = document.querySelector("div[value=444]");
target.parentNode.insertBefore(div, target);
Or using the DOM's insertAdjacentHTML:
document.querySelector("div[value=444]").insertAdjacentHTML(
"beforebegin",
"<div value=333></div>"
);
Side note: div is not a void element, <div /> isn't a self-closing tag, it's a start tag with a / in it that's ignored.
Side note 2: value is not a valid attribute for div elements.
I am using pure JS to append a HTML string after a div that has been found by getElementById. This is working correctly but I would now like to append after the first child of the found element.
JSFiddle
HTML
First Div
Div I want to append to
Other div...
(the second and third divs have no id or class)
JS
function insertAfter(referenceNode, newNode) {
referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}
var element1 = document.createElement("div");
element1.innerHTML = 'Text to append';
var div1 = document.getElementById('first-div');
insertAfter(div1, element1);
Current result is:
First Div
Div I want to append to
Other div...
Text to append
I am trying to achieve this:
First Div
Div I want to append to
Text to append
Other div...
I have tried
var div1 = document.getElementById('first-div').firstchild;
but this is not working
As I said in my comment, your example suggests the div you want to append to is not the child, but rather the sibling of "first-div". It should look like
<div id="first-child">
<div>Div I want to append to</div>
</div>
Then the first child of the parent div can be found with
var div2 = div1.children[0];
I fiddled with your fiddle:
http://jsfiddle.net/01qrmj36/
If you remove the referenceNode from the insertBefore call in your insertAfter example it should behave how you want it to, eg:
function insertAfter(referenceNode, newNode) {
referenceNode.parentNode.insertBefore(newNode);
}
var element1 = document.createElement("div");
element1.innerHTML = 'Text to append';
var div1 = document.getElementById('first-div');
insertAfter(div1, element1);
Omitting the referenceNode from insertBefore defaults to inserting the new node at the end of the list of child nodes, see more here.
I have an array of elements from my webpage which I am trying to then insert some html, stored as a variable into a matching array item. For example
<div class="play">
<div>
<p>Item to be inserted after this p tag</p>
</div>
</div>
var elements = $('.play');
//elements length = 4;
var item = '<p>HTML to be inserted</p>'
$(item).appendTo(elements[1]);
In the above code I am trying to insert 'item' into the second value in the array within the child div shown in the html, however I am unsure how to insert it into the child div. At present this inserts 'item' after the parent html tag containing .play.
Any help would be greatly appreciated.
Note that elements isn't an array, it's a jQuery object, which means you can use jQuery methods to traverse through the DOM:
elements.eq(1).find("div").append(item);
Demo: http://jsfiddle.net/rgQ7g/
.eq(1) selects the second item but returns it wrapped in another jQuery object, so then you can use .find("div") to get to the child div and .append() your item to it.
Try after():
$('.play').find('p').after(item);
This inserts content AFTER a selected element in the DOM. It also does it for all the classes named .play
If you need to specify an index, I recommend a function:
function appendPlay(index, content) {
$('.play').eq(index).find('p').after(content);
}
appendPlay(2, '<p>HTML to be inserted</p>');
jsFiddle
please try using
var element = $('.play div p');
var item = '<p>HTML to be inserted</p>'
$(element).parent().append(item);
Edited
from
var element = $('.play div');
var item = '<p>HTML to be inserted</p>'
$(element).append(item);
Well, I guess this would work:
$(item).appendTo($(elements));
But a better solution would be using:
$('.play').find('p').after(item);
You can use link below. (I edited code after comment)
You should write code like;
var selector = ".play",
text = "<p>HTML to be inserted</p>";
$(selector + " div p").eq(1).after(text);
http://jsbin.com/esesul/5/
http://www.frostjedi.com/terra/scripts/demo/jquery02.html
According to this link elements can be moved around by doing $('#container1').append($('#container2')). Unfortunately, it doesn't seem to be working for me. Any ideas?
See jsfiddle http://jsfiddle.net/Tu7Nc/1/
You must append not your div exactly, but your div's content(inner HTML) with Jquery's html() function.
HTML:
<div id="1">aaa</div>
<div id="2">bbb</div>
Jquery:
$("#1").append($("#2").html());
Result:
aaabbb
bbb
It is best not to use html().
I ran into some issues due to html interpreting the contents as a string instead of a DOM node.
Use contents instead and your other scripts should not break due to broken references.
I needed to nest the contents of a DIV into a child of itself, here is how I did it.
example:
<div id="xy">
<span>contents</span>
</div>
<script>
contents = $("#xy").contents(); //reference the contents of id xy
$("#xy").append('<div class="test-class" />'); //create div with class test-class inside id xy
$("#xy").find(">.test-class").append(contents); //find direct child of xy with class test-class and move contents to new div
</script>
[EDIT]
The previous example works but here is a cleaner and more efficient example:
<script>
var content = $("#xy").contents(); //find element
var wrapper = $('<div style="border: 1px solid #000;"/>'); //create wrapper element
content.after(wrapper); //insert wrapper after found element
wrapper.append(content); //move element into wrapper
</script>
To move contents of a div (id=container2) to another div (id=container1) with jquery.
$('#container2').contents().appendTo('#container1');
You can also do:
var el1 = document.getElementById('container1');
var el2 = document.getElementById('container2');
if (el1 && el2) el1.appendChild(el2);
or as one statement, but not nearly as robust:
document.getElementById('container1').appendChild(document.getElementById('container2'));
Edit
On reflection (several years later…) it seems the intention is to move the content of one div to another. So the following does that in plain JS:
var el1 = document.getElementById('container1');
var el2 = document.getElementById('container2');
if (el1 && el2) {
while (el2.firstChild) el1.appendChild(el2.firstChild);
}
// Remove el2 if required
el2.parentNode.removeChild(el2);
This has the benefit of retaining any dynamically added listeners on descendants of el2 that solutions using innerHTML will strip away.
$('#container1').append($('#container2').html())
Well, this one could be an alternative if you want to Append:
document.getElementById("div2").innerHTML=document.getElementById("div2").innerHTML+document.getElementById("div1").innerHTML
if you wanted to rewrite contents:
document.getElementById("div2").innerHTML=document.getElementById("div1").innerHTML
I suggest a general approach with a function and jQuery:
function MoveContent(destId, srcId) {
$('#' + destId).append($('#' + srcId).contents().detach());
}
Content of a detached source node is appended to a destination node with call:
MoveContent('dest','src');
The first parameter is an id of a new parent node (destination), the second is an id of an old parent node (source).
Please see an example at: http://jsfiddle.net/dukrjzne/3/
If i have an HTML element like <div> with some text inside or another elements can I add before or after this div some text data without an html element, just plain text?
I'd like to use only pure Javascript.
Something like :
<div id="parentDiv">
my text must be added here
<div id="childDiv"></div>
</div>
Yes, you can create a text node with document.createTextNode('the text')
Then you can insert it like an element, with appendChild or insertBefore.
Example that insert a text before #childDiv:
var text = document.createTextNode('the text');
var child = document.getElementById('childDiv');
child.parentNode.insertBefore(text, child);
Just for the record:
div.insertAdjacentHTML( 'beforeBegin', yourText );
where div is your child-DIV.
Live demo: http://jsfiddle.net/ZkzDk/
If you just need text, I find that element.insertAdjacentText(position, text) is flexible for many scenarios and is also compatible with older browsers like IE6. Where position is exactly where you want the text to be and text is the text node or just a string. The options are:
'beforebegin' Before the element itself.
'afterbegin' Just inside the element, before its first child.
'beforeend' Just inside the element, after its last child.
'afterend' After the element itself.
Like this:
let div = document.getElementById('parentDiv');
div.insertAdjacentText('afterbegin', 'My Plain Text..');
In regards to the topic and the users question for inserting before or after, here is an example for after:
var text = document.createTextNode("my text must be added here.");
var childTag = document.getElementById("childDiv");
childTag.parentNode.insertBefore(text, childTag.nextSibling);
If the childTag does not have any siblings, it is okay because the insertBefore method handles this case and simply adds it as the last child.
Also can possibly use the appendChild() method after creating text node then add your childTag via the parentNode.
You can add text node. Create node - document.createTextNode('text') and then insert/append/replace - do whatever you want.
Something like this should do it:
<script type="text/javascript">
var parent = document.getElementById('parentDiv');
var sibling = document.getElementById('childDiv');
var text = document.createTextNode('new text');
parent.insertBefore(text, sibling);
</script>