0

If I have a variable defined in jquery as follows:

var insertString = "<div id='divid'>";
    insertString += "<input type='text' name='textbox' value=''>";
    insertString += "</div>";

Now, if I want to insert the above variable 'insertString' before some DOM element, how can I do it? I tried Something like below with no success

  insertString.insertBefore("body");
8
  • A string does not have an insertBefore method, only jQuery objects do. You might want to try: $('body').prepend(insertString). Commented May 31, 2011 at 14:18
  • @pimvdb, that'll insert the string right after <body> which isn't what is asked for (although is quite possibly what is wanted). Commented May 31, 2011 at 14:20
  • @tjm: I don't really know - why would you insert a div before the body element anyway? Commented May 31, 2011 at 14:22
  • @tjm: After? Look up what "prepend" means. Commented May 31, 2011 at 14:22
  • use $('body').appendTo(insertString); //jQuery will convert your string into DOM nodes. Cha ching! Commented May 31, 2011 at 14:22

3 Answers 3

3

I would not recommend inserting that before the body tag as that content belongs inside of it, but here's how you would insert it before an element with id='foo'.

$(insertString).insertBefore('#foo');

Update: Here's a fiddle to test the functionality

Sign up to request clarification or add additional context in comments.

Comments

3

Don't insert before the body. Contents goes in the body.

Why not prependTo instead?

Also, you attempt to run a jQuery member function on a string, not on a jQuery object. You need to form the jQuery object from the string.

Finally, you forgot to close your input tag.

Like this:

$(function() {
    var insertString = "<div id='divid'>";
    insertString += "<input type='text' name='textbox' value='' />";
    insertString += "</div>";

    $(insertString).prependTo("body");
});

Comments

2

You should be able to wrap your html in a $() function thus passing it to jQuery and creating a jquery object. Then you can operate on that object by chaining jQuery functions like this:

$(insertString).insertBefore("body");

But it would be pretty weird to put a div BEFORE the body... maybe it is better to prepend it to the body like this...

$(insertString).prependTo("body");

1 Comment

You mean prependTo, or reverse the target and source.

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.