You are here:Home»KB»Programming»Javascript»Append HTML or Text to page elements with javascript
Sunday, 22 February 2015 21:08

Append HTML or Text to page elements with javascript

Written by

The following snippets are simple methods of adding HTML and text in to the DOM tree with javascript.

//Add some text in to the variable sometext - note it adds it as text not html - also next section is required
var sometext = document.createTextNode("Z<br /><br />");

// This appends the variable some text to cellRightSel
cellRightSel.appendChild(sometext);

//--

// This adds the text straight on to cellRightSel, no variable required
cellRightSel.appendChild(document.createTextNode('Here is some syndicated content.'));

//-

// didnt work
cellRightSel.appendChild(create('<div>Hello!</div><br /><br />'));

//-

// this makes a variable newElement populated with the following html (this does actually paste the html)
var newElement = '<p id="foo">This is some dynamically added HTML. Yay!</p>';
var bodyElement = cellRightSel;
bodyElement.innerHTML = newElement + bodyElement.innerHTML;

// same as above but shorter and quickr, you can probably alter the order appropiately
cellRightSel.innerHTML = '<p id="foo">This is some dynamically added HTML. Yay!</p>' + cellRightSel.innerHTML;

 

Read 1261 times Last modified on Sunday, 22 February 2015 21:14