user1022521
user1022521

Reputation: 537

JQuery foreach, select multiple spans and add to Div

I am trying to loop through each <span> element individually and add it with some individual html, with my js even with foreach, it is always alerting all the elements as one entity. Any suggestions on where it is going wrong here...

$("#testDiv").html("");
$("#main span b").each(function () {
     alert($('#main span b').text());
     $("#testDiv").append($("<span/>", {
         class: 'adkeys',
         html: $('#main span b').text() + "<a class='anch'>"
     }));
});

For my following fiddle:

http://jsfiddle.net/LEe7B/

Upvotes: 0

Views: 1178

Answers (2)

Ananthan Unni
Ananthan Unni

Reputation: 1304

You can either use $(this) inside the loop body or write as in the following...

$('yourselector').each(function(index,value){
 alert($(value).text());
});

Upvotes: 0

adeneo
adeneo

Reputation: 318232

Use the this keyword inside the loop, not the selector again

$("#testDiv").html("");

$("#main span b").each(function () {
     alert($(this).text());

     $("#testDiv").append($("<span/>", {
         'class' : 'adkeys',
         html    : "<a class='anch'>" + $(this).text() + "</a>"
     }));

});

FIDDLE

Upvotes: 1

Related Questions