Append and Prepend without JQuery?

Hi,

I am trying to write the following in JavaScript without the help of JQuery.

$("head").append('<link rel="stylesheet" type="text/css" href="style.css" />');
$("body").prepend('<p>My content goes here</p>');

Is there a way to do that?

Thanks for any ideas.


var e = document.createElement('p');
e.innerHTML = 'My content goes here';
document.body.insertBefore(e, document.body.childNodes[0]);

$("head").append('<link rel="stylesheet" type="text/css" href="style.css" />'); 

you could replace with

var newLink = document.createElement("link");
newLink.href = "style.css";
newLink.setAttribute('rel', 'stylesheet');
newLink.setAttribute('type', 'text/css');

document.head.appendChild(newLink);

Variant:


var e = document.createElement('p');
var t = document.createTextNode("My content goes here");
e.appendChild(t);
document.body.insertBefore(e, document.body.childNodes[0]);

Thanks a lot. What if I have dynamic HTML in

$("body").prepend('no idea what HTML will be here');

Thank you very much! It worked.

Once you have created the element e, you have a javascript object on your hands.
You either access its innerHTML property (first example), or build its content with appendChild (second example).
Both are dynamic:

e.innerHTML = e.innerHTML + '<span>More of my content</span>'
var s = document.createElement('span');
var t = document.createTextNode("More of my content");
s.appendChild(t);
e.appendChild(s);

e.innerHTML or e.appendChild can be augmented with any type of content.

Thank you very much, I added a div and then the dynamic content within that div and it works fine now.