Luke Luke - 6 months ago 11
Javascript Question

Add single rel value to all <a> in parent and also add incremental rel values to <a> of sibling parents

Horrible title I know. I'm looking to apply a specific rel value to all child

<a>
within a parent, in this case
.wrap
. All rel values should be the same within a particular instance of
.wrap
, but between each individual
.wrap
(i.e. the siblings of a parent) the rel values should have a numeric distinction.

In the example below this rel value takes the form of
rel="type-X"
where X is the incremental numeric value. This is what I want.

<div class="wrap">
<div><a rel="type-1" href="#"></a></div>
<div><a rel="type-1" href="#"></a></div>
<div><a rel="type-1" href="#"></a></div>
</div>
<div class="wrap">
<div><a rel="type-2" href="#"></a></div>
<div><a rel="type-2" href="#"></a></div>
<div><a rel="type-2" href="#"></a></div>
</div>
<div class="wrap">
<div><a rel="type-3" href="#"></a></div>
<div><a rel="type-3" href="#"></a></div>
<div><a rel="type-3" href="#"></a></div>
</div>


The best I've been able to come up with so far is to either either apply the same rel value to all instances of
.wrap a
(so just one instance of rel="type-1" in all 3 .wrap) or I'm applying a new rel value to each
<a>
(and end up with rel="type-1" to rel="type-9")



var i = 0;
$('.wrap').find(function () {
i ++;
$(this).find('a').attr('rel', 'type-' + i);
});

Answer

You may write:

$('.wrap').each(function(index, element) {
    $(this).find('a').attr('rel', 'type-' + (index + 1));
});

$(function () {
  $('.wrap').each(function(index, element) {
    $(this).find('a').attr('rel', 'type-' + (index + 1));
  });
  
  $('#txtarea').text($('#myBlock').html())
  .height($('#txtarea')[0].scrollHeight);
  
  $('#addRel').on('click', function(e) {
     $('.wrap').each(function(index, element) {
       $(this).find('a').attr('rel', 'type-' + (index + 1));
     });
    $('#txtarea').text($('#myBlock').html());
  });

  $('#removeRel').on('click', function(e) {
    $('.wrap').each(function(index, element) {
       $(this).find('a').removeAttr('rel');
     });
    $('#txtarea').text($('#myBlock').html());
  });
});
<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>

<div id="myBlock">
    <div class="wrap">
        <div><a href="#"></a></div>
        <div><a href="#"></a></div>
        <div><a href="#"></a></div>
    </div>
    <div class="wrap">
        <div><a href="#"></a></div>
        <div><a href="#"></a></div>
        <div><a href="#"></a></div>
    </div>
    <div class="wrap">
        <div><a href="#"></a></div>
        <div><a href="#"></a></div>
        <div><a href="#"></a></div>
    </div>
</div>
<textarea id="txtarea" style="width: 100%;"></textarea>
<button id='addRel'>Add Rel Attr</button>
<button id='removeRel'>Remove Rel Attr</button>