Home > Software engineering >  Get attribute of element for multiple with same class
Get attribute of element for multiple with same class

Time:08-16

I am trying to get the attribute "data-index" on click of each of these indicators. On click it is currently stating undefined.

var dot = $('.dot');
for( var i = 0; i < dot; i   ){
   $(dot[i]).attr("data-index");
}

$(dot).click(function() {
  var slideNumber = $(this).attr("data-index");
  console.log(slideNumber);
});
.dot {
  width: 6px;
  height: 6px;
  border-radius: 20px;
  position: relative;
  background-color: #D2D2D2;
  margin: 0 5px;
  cursor: pointer;
  display: inline-block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div ></div>
<div ></div>
<div ></div>
<div ></div>
<div ></div>

CodePudding user response:

Found 2 issues in your code :

  1. You are using the wrong operator in for loop for iterating over the elements. You would need to use i < dot.length.

  2. You need to set the value of attr by passing it as the second argument to the attr function.

Check the running snippet below.

var dot = $('.dot');
for( var i = 0; i < dot.length; i   ){
   $(dot[i]).attr("data-index", i 1);
}

$(dot).click(function() {
  var slideNumber = $(this).attr("data-index");
  console.log(slideNumber);
});
.dot {
  width: 6px;
  height: 6px;
  border-radius: 20px;
  position: relative;
  background-color: #D2D2D2;
  margin: 0 5px;
  cursor: pointer;
  display: inline-block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div ></div>
<div ></div>
<div ></div>
<div ></div>
<div ></div>

  • Related