Question

as seen in this Fiddle i want to change the value of another div using the unique id of one div but i dont know how to make that possible it only works for the first div not the second one

Code:

html

<div class="a" data-u="1399037905154655004">a</div>
<div class="a" data-u="1399037905154655009">b</div>
<br>
<div class="test" id="id1399037905154655004">ini text 1</div>
<div class="test" id="id1399037905154655009">ini text 2</div>

Javascript

var id=$(".a").attr('data-u');//get the id
$("#id"+id).text("23456");//using the unique id change the text 

Note:I donot want to use any form of click event

Was it helpful?

Solution

You need .each() with .data(), As .data() is to get data-attribute of the element

$(".a").each(function(){
    var id = $(this).data('u');
    $("#id"+id).text("23456") // Will set same text for both divs
}); 

As per your comment

If you prefer .attr() then try this

var id = $(this).attr('data-u'); // .attr instead of .data()

Note: If you're using data-attr anywhere in your mark-up, it is recommended to use .data() instead of .attr() to get that attribute.

Fiddle

Demo With .attr()

OTHER TIPS

You're using a class, to target your divs, so your selector is returning more than one element, you need to loop:

$(".a").each(function(){
    var id = $(this).data('u');
    $("#id"+id).text("23456")
}); 
  var id = $(".a").map(function(){return $(this).attr("data-u");}).get();

  $("#id"+id[0]).text("23456"); 
  $("#id"+id[1]).text("23456");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top