As the other explain you could use either .parents()
or closest()
.
Note that using either:
$(this).parents(".main").find("select").css("color", "red");
or
$(this).closest(".main").find('select').css("color", "red");
would target all select
.
The reason why when you click the link got scrolled to the top because you set href="#"
replacing with href="javascript:void(0)"
would solve the issue. See here for more explanation: Which “href” value should I use for JavaScript links, “#” or “javascript:void(0)”?
Adding more detailed selector would prevent targetting all select
element:
For selecting which element if you only had one you could use .first()
if you had more than one and possibly more :nth-child(x)
where x
is the index of your element.
To scroll and focus to select
you can use .focus()
. To smoothen the focus you could use .animate
:
$('html,body').animate({
scrollTop: $("select").first().offset().top
}, 'slow');
$("select").first().focus();
See the following snippet:
$(document).ready(function() {
$(".main .tst").on("click", function() {
//$(this).parents(".main").find("select").first().css("color", "red");
$(this).closest(".main").find('select').first().css("color", "red"); // removing first() would target all select element
});
$(".main .tfse").on("click", function() {
//$(this).parents(".main").find("select").first().css("color", "green");
$(this).closest(".main").find('select').first().css("color", "green"); // removing first() would target all select element
$("select").first().focus();
});
$(".main .tfsa").on("click", function() {
//$(this).parents(".main").find("select").first().css("color", "orange");
$(this).closest(".main").find('select').first().css("color", "orange"); // removing first() would target all select element
$('html,body').animate({
scrollTop: $("select").first().offset().top
}, 'slow');
$("select").first().focus();
});
$(".main .tise").on("click", function() {
//$(this).parents(".main").find("select:nth-child(2)").css("color", "blue");
$(this).closest(".main").find('select:nth-child(2)').css("color", "blue");
$('html,body').animate({
scrollTop: $("select:nth-child(2)").offset().top
}, 'slow');
$("select:nth-child(2)").focus();
});
})
.sub-2{
margin-top:1600px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="main">
<div class="sub-1">
<select>
<option>1</option>
<option>2</option>
</select>
<select>
<option>1</option>
<option>2</option>
</select>
</div>
<div class="sub-2">
<a href="javascript:void(0)" class="tst">Only affect but not focus (red, first)</a><br/>
<a href="javascript:void(0)" class="tfse">Target and focus select element (green, first)</a><br/>
<a href="javascript:void(0)" class="tfsa">Target, animate scroll and focus select element (orange, first)</a><br/>
<a href="javascript:void(0)" class="tise">Target, animate scroll and focus select element based on your selected index - this example target second -> :nth-child(2) (blue, second)</a>
</div>
</div>