locateganesh locateganesh - 12 days ago 5
Javascript Question

Class by index or data-attr

I have this code:

var i = 1;
if ($(this).attr('data-target="1"')){}


Now I want to pass i variable instead of 1.

if ($(this).attr('data-target="'+i+'"')){}


Am i right?

actually what I want to do. I want to click
li
on click of
h2
data-target
in for loop. Is there any other solution for target multiple elements by one code?

find fiddle

VPK VPK
Answer

You don't have element with class ul,

Just try this,

$('.UDSHead').click(function(){
  var dataTarget = $(this).data('target');
  $('li:eq('+ (dataTarget - 1) +')').addClass('highLight');
});

Also, you don't need to bind event in the for loop.

Example

Comments