t.x
t.x

Reputation: 83

jQuery Loop by id for each element

hi i have some problem about logic of loop

have a few elements

<div place="1" area="Text 1" class="element"></div>
<div place="2" area="Text 2" class="element"></div>
<div place="3" area="Text 3" class="element"></div>

and

<span place="1"></span>
<span place="2"></span>
<span place="3"></span>

and i want to insert all div elements area attribute value to span element which place are the same


like this

<span place="1">Text 1</span>
<span place="2">Text 2</span>
<span place="3">Text 3</span> 

Upvotes: 5

Views: 6488

Answers (4)

Bourbia Brahim
Bourbia Brahim

Reputation: 14702

See below answer using jQuery

$(document).ready(function(){

  $("div[place]").each(function(i,el){
    $("span[place='"+$(this).attr("place")+"']").html($(this).attr("area"));
  })
  
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div place="1" area="Text 1" class="element"></div>
<div place="2" area="Text 2" class="element"></div>
<div place="3" area="Text 3" class="element"></div>

<span place="1"></span>
<span place="2"></span>
<span place="3"></span>

Upvotes: 1

Aldo Sanchez
Aldo Sanchez

Reputation: 450

You can do something like this:

$('.element').each(function(i, obj) {
    var area= $(obj).attr('area');
    var span = $('<span></span>');
    span.attr('place', i);
    span.text(area);
});

Upvotes: 0

Thomas Rbt
Thomas Rbt

Reputation: 1538

You should use data- attribute to make something like :

$( ".element" ).each(function(  ) {
  var place = $(this).attr("data-place");
  var area = $(this).attr("data-area");

  $('.place-'+place).html( area );
});

And your HTML structure should look that:

<div class="element" data-area="test 1" data-place="1"></div>
<div class="element" data-area="test 2" data-place="2"></div>
<div class="element" data-area="test 3" data-place="3"></div>


<span class="place-1"></span>
<span class="place-2"></span>
<span class="place-3"></span>

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337560

Firstly note that creating your own non-standard attributes in your HTML can lead to some odd behaviour. It's much better practice to use data attributes to store any custom metadata with an element.

To fix your actual issue, you need to loop through all the div elements, then select the span with the related place and set its text(), like this:

$('.element').each(function() {
  $('span[data-place="' + $(this).data('place') + '"]').text($(this).data('area'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-place="1" data-area="Text 1" class="element"></div>
<div data-place="2" data-area="Text 2" class="element"></div>
<div data-place="3" data-area="Text 3" class="element"></div>

<span data-place="1"></span>
<span data-place="2"></span>
<span data-place="3"></span>

Note the use of data-* attributes in the example.

Upvotes: 7

Related Questions