Senthil
Senthil

Reputation: 83

How to add an element to 'body' using Prototype?

I have created an element like this:

var myDiv = new Element('div');
myDiv.update('Hello!');

I want to add myDiv to body.

I tried

$('body').insert(myDiv);

But it is not working. I also tried

$('body')[0].insert(myDiv);

thinking that $('body') was returning an array. Even that didn't work.

How can I add myDiv to body?

Thanks.

Upvotes: 8

Views: 14854

Answers (4)

Salman Arshad
Salman Arshad

Reputation: 272266

$ is a shorthand for document.getElementById(), $$ is the more versatile prototype function. To access the (first) body element in your document, use:

$$('body')[0].insert(myDiv);

Upvotes: 7

winkbrace
winkbrace

Reputation: 2711

As Pekka said, you first need to extend document.body with Prototype's DOM extensions to be able to use Prototype's insert() method. Although Firefox seems to somehow be able to execute the insert() anyway :)

for more information: http://www.prototypejs.org/learn/extensions

Upvotes: 1

denisjacquemin
denisjacquemin

Reputation: 7414

$$('body')[0] works fine

Upvotes: 1

Pekka
Pekka

Reputation: 449663

How about

$(document.body).insert(myDiv);

?

Differently from jQuery, in Prototype, $('body') fetches the element with the id body.

Upvotes: 15

Related Questions