Verde Mc Verde Mc - 5 months ago 22
jQuery Question

Jquery length not working with elements with variable in name

It works if you put only

$('li').lenght;


length is not working if you add a variable to the name
$('#id_'+variable).length;


<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
var tu = '1';
alert($("#uno_"+tu).length);

// IT WORKS IF YOU PUT ONLY $('li').lenght;
});
});
</script>
</head>
<body>

<button>Alert the number of li elements</button>

<ul>
<li id="uno_1">Coffee</li>
<li id="uno_1">Milk</li>
<li id="uno_1">Soda</li>
</ul>

</body>
</html>

Answer

Id can not be duplicated in html, Id should be unique for each element in the page, but you can use class here instead of Id.

$(document).ready(function(){
   $("button").click(function(){
      var tu = '1';
      alert($(".uno_"+tu).length);
   });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<button>Alert the number of li elements</button>

<ul>
  <li class="uno_1">Coffee</li>
  <li class="uno_1">Milk</li>
  <li class="uno_1">Soda</li>
</ul>