JQuery Loop by id for each element
Hi i have a problem about loop logic
have multiple 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 the scope attribute attributes of a div element into a span element whose position matches
like this
<span place="1">Text 1</span>
<span place="2">Text 2</span>
<span place="3">Text 3</span>
source to share
First, please note that creating your own custom attributes in your HTML may result in some odd behavior. It is much better to use attributes data
to store any custom metadata with an element.
To fix your actual problem, you need to skip all items div
, then select span
with the linked one place
and install it text()
, for example:
$('.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 attributes data-*
in this example.
source to share
See below answer with 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>
source to share
You have to use the data attribute to do 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 like this:
<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>
source to share