简体   繁体   中英

How to get previous element which has a specific element?

I need to select the element for previous element which holds a specific element. Hard to understand let me explain in that way.

HTML (DOM):

<div><a></a></div>

<div><p class="selectThis"></p></div> ------
                                           -
<div><a></a></div>                         - select from previous element which holds class
                                           -
<div><p class="fromThis"></p></div> --------

What I tried before:

 $('.fromThis').parent().prev(); //

This isn't the prettiest, but it selects the element and adds a class

jQuery solution

 $("a").on("click", function(event) { event.preventDefault(); $(this).parent().prevAll().find(".selectThis").css({"background": "gold"}); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div><a></a></div> <div><p class="selectThis">This is a paragraph</p></div> <div><a href="www.google.com">Select previous class</a></div> <div><p class="fromThis"></p></div>

When you click on a link, the default behavior is to open a new tab. To prevent this, we can call the preventDefault action.

To find the div with a class of selectThis , we traverse upward to find the parent element, traverse backwards to find its sibling element. To find the sibling's children, we use the find() method.

You could do

 $('.fromThis').parent().prevAll().find('.selectThis');

From the level of the divs you will select all previous siblings (ie the other divs) on this level. Then all descendants of the divs with the selectThis class are selected. So it does not only necessarily select on element or the closest to fromThis but a whole set of elements if there are more.

If it is important that you only select the element closest to your original element, you have to extend the expression like this:

 $('.fromThis').parent().prevAll().find('.selectThis').last();

我的解决方案是:找到第一个父级,然后是所有的兄弟级,然后过滤类:

$('.fromThis').parent().siblings().find('.selectThis')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM