Tutorial :Adding HTML elements with JavaScript



Question:

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?


Solution:1

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);  


Solution:2

node = document.getElementById('YourID');  node.insertAdjacentHTML('afterend', '<div>Sample Div</div>');  

Available Options

beforebegin, afterbegin, beforeend, afterend


Solution:3

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.


Solution:4

If you want to use something like jQuery you can do something like this:

$('#div a').after("Your html element");  


Solution:5

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.


Solution:6

Assuming that you are only adding one element:

document.getElementById("div").insertBefore({Element}, document.getElementById("div").children[2]);  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »