0

Can you guys please help me with this jsFiddle?: http://jsfiddle.net/4CNKa/2/

I am trying to create new (hidden) objects [ $(object) ] on the fly...with jQuery...but so far, I had no luck. In this jsFiddle it's a div, but I want to be able to create any kind of $()

$(document).ready(function() {
    $("#msg") = '<div id="msg"></div>';
    $("#msg").html('<p id="test">My <em>new</em> text</p>');

    //FOR TESTING         
    alert( $("#msg").text() ); //FOR TESTING ONLY!!!
    $("#msg").appendTo('body'); //FOR TESTING ONLY!!!
});

2 Answers 2

2

Try this:

$(document).ready(function() {
    var div  = $('<div id="msg"></div>');
    div.html('<p id="test">My <em>new</em> text</p>');

    //FOR TESTING         
    alert( div.text() ); //FOR TESTING ONLY!!!
    div.appendTo('body'); //FOR TESTING ONLY!!!
});

Fiddle: http://jsfiddle.net/maniator/4CNKa/3/

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

5 Comments

Thanks, but I wanna reference the object as $("#msg") instead of div.something .
@Omar not sure why you want to do that. because every time you do $('#msg') it has to search the dom. later on you can to $('#msg') but not when the div was not created yet.
@Omar - Do you understand what a jQuery selector is?
I thought $() refers to objects
I I want to use your example with UI dialog, how will it work?
1

You can create new elements in jQuery like this:

var el = $("<div class='className' />").html("Hello World!");
el.appendTo($("#container"));

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.