简体   繁体   中英

How to create an html object and append sibling to that from an array using JQuery?

var html=$("<span>Number</span>"); 

$.each([1,2,3,4,5],function(index,item){
    html.add($("<span>"+item+"</span>"));
});

From the above sample code, "html" - is span object. I want to append all array elements as sibling for this "html" object.

Expectation result:

[1,2,3,4,5] -> total 5 elements bind as span objects with sibling of "html" object.

Actual result :

if i try to use add or append its binding as a child element of "html" object.

Please guide me.. Thanks on advance!

Try:

html = html.add($("<span>"+item+"</span>"));

The documentation says that it returns a new collection, not changing the existing one.

You don't really need a jQuery object to do this, you can just build a HTML string and then use it however you like

See the example below.

 var html = "<span>Number</span>"; $.each([1, 2, 3, 4, 5], function(index, item) { html += "<span>" + item + "</span>"; }); $("#insert").append(html); 
 span { display: block; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="insert"></div> 

I think jQuery and HTML is confusing you. I can also see a little mistake in the query passed.

All you need to do is define a list, add items and user $("listid").append(item1,item2);

To repeat the word span 6 times, make your object work like an array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM