Mark Timothy
Mark Timothy

Reputation: 1814

Copy childs' attribute and value to parent using jquery

I have something like this

<div>
 <span id="1"></span>
</div>
<div>
 <span id="2"></span>
</div>
<div>
 <span id="3"></span>
</div>

I need the id of each span to be put in to its parent div

result should be something like this

<div id="1">
 <span></span>
</div>
<div id="2">
 <span></span>
</div>
<div id="3">
 <span></span>
</div>

Upvotes: 2

Views: 490

Answers (4)

Alnitak
Alnitak

Reputation: 339786

Fastest solution, using direct DOM manipulation and avoiding using jQuery within the loop: Also, starting with the spans themselves instead of the divs makes it easier to work with the parent.

$('span[id]').each(function() {  // only consider spans with an ID
    var id = this.id;            // get the original ID
    this.id = null;              // remove it from the span
    this.parentNode.id = id;     // and give it to its parent
});

This could strictly be one line shorter (this.parentNode.id = this.id; this.id = null) but as written it ensures that the ID is never on two elements at once.

Upvotes: 1

Stiger
Stiger

Reputation: 1199

Try:

$('div').each(function(item){ // loop all divs
    var $span =  $($(this).children('span')); // find the "span" tag inside "div", "this" in this context is "div" tag
    $(this).attr('id', $span.attr('id')); // update id for "div" tag
    $span.removeAttr('id'); // remove id of "span" tag
});

Upvotes: 0

Dinesh Mandaviya
Dinesh Mandaviya

Reputation: 192

Try below

$("div span").each(function(){
   $(this).parent().attr("id",$(this).attr("id"));
   $(this).removeAttr('id');
});

Upvotes: 2

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67187

Try to use .attr()'s receiver function to accomplish your task,

$('div').attr('id',function(){
 return $(this).children('span').attr('id');
}).children('span').removeAttr('id');

DEMO

Upvotes: 2

Related Questions