AGN AGN - 6 months ago 22
Javascript Question

How do I select the nth child of an element?

I need to change the display style of three stacked pictures based on the picture I hover on. Apparently it's impossible to go up to the parent and to the next with CSS

:hover
.

I tried to use parts of code I found to get it working. JavaScript works on the first child but I can't get it to display the 2nd child instead.

HTML:

<div class="c-tab is-active">
<div class="c-tab__content">
<div class="row" id="mapviewer">
<div class="col-xs-4 nopadding" style="" id="d_d2">
<div class="dd21 viewer1" id="test111">
<img class="map" src="images/d/dd2.png" >
<img class="map" src="images/hover1/mockuptopage_01.png" >
<img class="map" src="images/hover2/mockuptopage_01.png" >
</div>
</div>
<div class="col-xs-4 nopadding" style="" id="n_d2">
<div class= "nd21 viewer2" id="test222">
<img class="map" src="images/n/dd2.png" >
<img class="map" src="images/hover2/mockuptopage_03.png" >
<img class="map" src="images/hover3/mockuptopage_01.png" >
</div>
</div>
<div class="col-xs-4 nopadding" style="" id="s_d2">
<div class="sd21 viewer3" id="test333">
<img class="map" src="images/s/dd2.png">
<img class="map" src="images/hover2/mockuptopage_03.png">
<img class="map" src="images/hover3/mockuptopage_01.png" >
</div>
</div>
</div>
</div>




JS:

$('#test111').on('mouseover', function() {
(document).getElementById("test222 img:nth-child(2)").style.display = "inline-block";
}).on('mouseout', function() {
(document).getElementById("test222:nth-child(2)").style.display = "none";
})

Answer

You should use the jQuery selectors, :nth-child() Selector

$('#test111').on('mouseover', function() {
    $("#test222 img:nth-child(2)").css('display', "inline-block");
}).on('mouseout', function() {
    $("#test222 img:nth-child(2)").css('display', "none");
})
Comments