开发者

append an element to another one and append all of them to another element

开发者 https://www.devze.com 2023-04-08 22:22 出处:网络
I want to create a div and append one ul (with a class) and one h5 (with text)开发者_JAVA百科 to it. then, append that div to another element.

I want to create a div and append one ul (with a class) and one h5 (with text)开发者_JAVA百科 to it. then, append that div to another element.

I think this code should do it:

$("div").addClass( "nice" )
    .append( $("ul").addClass("myclass") )
    .append( $("h5").text("heading") )
    .appendTo( $("#another_div") );

but it doesn't work and browser crashes!

How? (i know i can use $("div").html(), but i don't like it!)

Thank you.


Your problem is that by using "div" and "ul" as your selectors, jQuery is searching the dom instead of creating elements. Try this:

$("<div></div>").addClass( "nice" )
    .append( $("<ul></ul>").addClass("myclass") )
    .append( $("<h5></h5>").text("heading") )
    .appendTo( $("#another_div") );


Live example: http://jsfiddle.net/kzLmp/

$(function(){
    $("<div>").addClass( "nice" )
    .append( $("<ul>").addClass("myclass") )
    .append( $("<h5>").text("heading") )
    .appendTo( $("#another_div") );
});
0

精彩评论

暂无评论...
验证码 换一张
取 消