Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding HTML elements with JavaScript

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?

like image 360
John Stimac Avatar asked Aug 06 '10 15:08

John Stimac


People also ask

How do you append an element in HTML?

HTML code can be appended to a div using the insertAdjacentHTML() method. However, you need to select an element inside the div to add the code. This method takes two parameters: The position (in the document) where you want to insert the code ('afterbegin', 'beforebegin', 'afterend', 'beforeend')


2 Answers

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

Available Options

beforebegin, afterbegin, beforeend, afterend

like image 123
Saqib R. Avatar answered Sep 24 '22 01:09

Saqib R.


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);
like image 36
simplyharsh Avatar answered Sep 25 '22 01:09

simplyharsh