Shane
Shane

Reputation: 5677

Accessing children of div and appending span

I am accessing my children like this, i am trying to set the span title for the each div container.

$(".div-container").children().each(function(n, i){    
    console.log("Is it coming" + this.id);
    $(this.id).before($('<span />').css('margin-left' , '60px').attr({'class':'progress-title' }).html('Title'));
    $(this.id).before($('<span />').attr({'class':'progress-title-after' }).html('25% Usage'));
});

I am getting the corresponding the id's, but the span element is not getting added to my div containers.

Upvotes: 0

Views: 82

Answers (2)

MrCode
MrCode

Reputation: 64526

this refers to the element, so you don't need to reselect it by ID. Just wrap this in a jQuery object.

$(this).before($('<span />').css('margin-left' , '60px').attr({'class':'progress-title' }).html('Title'));

Upvotes: 3

Dhaval Marthak
Dhaval Marthak

Reputation: 17366

Why not

$(this).before($('<span />').... // rest of code

instead of concatenating those IDs like

$(this.id).before($('<span />').... // rest of code

Because you're fetching IDs of each children so ultimately you're getting the object itself

Upvotes: 2

Related Questions