0

In the script below, i am inserting some code at the beginning of a DIV.

    var mydiv = document.getElementById("myDIV");
    var mycontent = document.createElement("p");
    mycontent.insertBefore(document.createTextNode("Hello <b>World</b><br><bR>"));
    mydiv.insertBefore(mycontent,mydiv.firstChild);

On my website, the code is inserted as text and the HTML formatting is ignored. Does anyone know how to have code inserted into a DIV using javascript?

1
  • if you got correct answer, please accept it ( click the checkmark under vote buttons) Commented Sep 18, 2012 at 11:21

3 Answers 3

2

You cannot insert tags, you can insert only DOM nodes. DOM nodes can be text nodes or element nodes (or a few others that you almost certainly don't care about).

The distinction is important since you can insert <div></div> but not <div>.

To create an element:

var myElement = document.createElement('div');

Your particular example:

var myContent = document.createElement('p');
myContent.appendChild(document.createTextNode('Hello'));
var bold = document.createElement('b'); // Please don't use presentational elements in 2012
bold.appendChild(document.createTextNode('World');
myContent.appendChild(bold);
myContent.appendChild(document.createElement('br')); // Please don't use line breaks as margin/padding substitutes
myContent.appendChild(document.createElement('br')); 
mydiv.insertBefore(mycontent,mydiv.firstChild);
Sign up to request clarification or add additional context in comments.

Comments

1

You can use in conjunction with an element and innerHTML for a simple solution:

var mydiv = document.getElementById("myDIV");
var mycontent = document.createElement("p");
mycontent.innerHTML = 'Hello <b>World</b><br><bR>';
mydiv.insertBefore(mycontent, mydiv.firstChild);

Comments

0

why not

var mydiv = document.getElementById("myDIV");
var mycontent = document.createElement("p");
mycontent.innerHTML = "Hello <b>World</b><br><bR>";
mydiv.insertBefore(mycontent,mydiv.firstChild);​

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.