views:

60

answers:

5

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?

A: 

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

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

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

Happy Coding.

simplyharsh
`document.getElementById('#div')` will be null, you probably meant `document.getElementById('div')`
Daniel Vandersluis
This is incorrect. *insertBefore* is not a global function, it's a method on the *HTMLElement* prototype. The correct method is `parentElement.insertBefore(newElement, childElement)`.
Andy E
Ah, my bad. Thanks.
simplyharsh
`insertAfter` is not an actual function either.
Daniel Vandersluis
A: 

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.

ford
A: 

Assuming that you are only adding one element:

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

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.

Daniel Vandersluis