How To Get or Select Child Element Of Previous Element In jQuery

Hello Friends,In this article I am going to explain how you can get first child element of previous element in jQuery. If you have ul li and a link below it then clicking on link you want to select first li of ul above link. Below I am going to explain how you can achieve it.

So I am taking one example, So I can explain all things easily. We have one ul with five li elements and below ul we have one link with id ‘test’. Now when page loads, on base of link we will select first li of above ul and make first li background color RED.Here is our HTML :

<ul>
<li>list item 1</li>
<li>list item 2</li>
<li>list item 3</li>
<li>list item 4</li>
<li>list item 5</li>
</ul>
<a id="test">Select First li from above ul</div>

Below is jQuery to select first li on the base of a link with id “test” :

$(function() {
   $('#test').prevAll("ul").children("li:first").css('background-color', 'red');
});

Now you can see in above code we just call jquery code when page load to select first child element of previous element. So when page load jQuery will get to previous ul then find first children of selected ul by using ‘children(“li:first”)’ and then make its background color RED.

Here is jsfiddle to see this example result live :

If you want to select first child of previous element by click on link or button then you can call click event and then use above code accordingly. I hope this code help you and save your time. If you have any other idea or trick to achieve same result then do let us know in comments.

I am PHP FreelancerHire PHP Developer India and PHP Freelancer India. If you have any projects related to WordPress or PHP you can contact me.

Subscribe to PHP Freelancer

Enter your email address: