Mateus Batista
Mateus Batista

Reputation: 11

Get "id" and add in each div (name = "id")

$(document).ready(function() {
    var idPost = $('.post-outer').attr('id');
    $('.post-outer').attr('name', idPost);
});

When you run the JS above it only takes the first "ID" repeating in other "DIV". What is going on:

<div class="post-outer" id="001" name="001">teste1</div>
<div class="post-outer" id="002" name="001">teste2</div>
<div class="post-outer" id="003" name="001">teste3</div>

I wanted to happen this:

<div class="post-outer" id="001" name="001">teste1</div>
<div class="post-outer" id="002" name="002">teste2</div>
<div class="post-outer" id="003" name="003">teste3</div>

Upvotes: 0

Views: 56

Answers (3)

Diptox
Diptox

Reputation: 1809

Demo

$('.post-outer .post-footer .post-footer-line.post-footer-line-2 .post-labels a').each(function(index, el) {
     $(this).parents('.post-outer:eq(0)').attr('itemtype', $(this).attr('href') );
});

Upvotes: -1

Barmar
Barmar

Reputation: 780788

The .attr() function can take a function as the argument. It calls the function repeatedly for each element (like .each() does), and the returned value is the new attribute value.

$('.post-outer').attr('name', function() {
    return this.id;
});

This is essentially equivalent to mevius's answer, but it doesn't call .attr() repeatedly.

Upvotes: 2

rnevius
rnevius

Reputation: 27092

Use the .each() method:

$('.post-outer').each(function() {
    $(this).attr( 'name', $(this).attr('id') );
});

Iterate over a jQuery object, executing a function for each matched element.

Upvotes: 3

Related Questions