Meek Meek - 18 days ago 8
HTML Question

Find corresponding elements

I have a set of divs with IDs going from "c1", "c2", "c3", etc. I would like to add a class to corresponding elements with IDs going from "b1", "b2", "b3" when hovering one of these divs. So c1 corresponds to b1, c2 to b2 and so on.

What is the best way to do this in jQuery?

I have been trying to experiment with some code on jsFiddle - obviously I couldn't make it work.

Html:

<div id="c1" class="event">c1</div>
<div id="c2" class="event">c2</div>
<div id="c3" class="event">c3</div>

<div id="t1" class="target">t1</div>
<div id="t2" class="target">t2</div>
<div id="t3" class="target">t3</div>


Js:

$('.event').hover(function() {
var getID = $(this).attr('id'); // get event ID
$(".target").each(function() {
var getTargetID = $(this).attr('id'); // get target ID
$("#" + $(this).attr('id') + xxx).addClass('newClas'); // <--- how to map the corresponding elements?
});
});


Is this the right approach?

Answer

You can achieve it using .index() and use .eq() to get the element at index. No need to depend upon IDs.

var targets = $(".target").removeClass('newClass');
var events = $('.event');
events.hover(function() {
    //Get current element index
    var index = events.index(this);

    targets.eq(index).addClass('newClass');
}, function() {
    targets.removeClass('newClass');
});

Updated Fiddle

If you still want to use Ids

events.hover(function() {
    var number = this.id.match(/\d+/)[0];
    $('#t' + number).addClass('newClass');
});

Updated Fiddle

Comments