Leron
Leron

Reputation: 9876

Get the closest previous element with a class using jQuery

I've looked through several very similar questions but couldn't get this work. What I have is this DOM structure:

<div class="container">
  <input class="selected"/>

  <div class="dropdown-wrapper ae-hide">
    <div class="selectable">1</div>
    <div class="selectable">2</div>
    <div class="selectable">3</div>
  </div>
</div>

when any of the .selectable is clicked I want to update the value of the input. The problem is that I can't find the correct selectors to do that. And this is dynamically created so I can have multiple html snippets like this one on my page that's why I'm using classes.

Here is the FIDDLE

Upvotes: 1

Views: 7724

Answers (4)

Luk&#225;š Ř&#225;dek
Luk&#225;š Ř&#225;dek

Reputation: 1441

.prev() gives you only the immediatelly previous element and if you specify a filter selector like this .prev('.selected') it only returns the previous element IF it matches that selector. Meaning if the desired .selected element is not immediately before the current element, it will return nothing.

If you truly want to get the closest previous element with a class (even if it is not immediately before the current element) you have to approach it like this.

currentElem
.prevAll('.selected') // returns all previous elems with 'selected' class in reverse DOM order (the closest is the first)
.eq(0); // return the first element in the set - the closest one

Therefore in your case

$('.selectable').click(function(){
  $(this).closest('.dropdown-wrapper').prevAll('.selected').eq(0).val('hit');
});

Upvotes: 1

Mahesh
Mahesh

Reputation: 873

One way to find element is :

$( ".selectable" ).parent().parent().find('input').val('somevalue');


$( ".selected" ).each(function(index) {
      $(this).on("click", function(){
       This is multiple elements have their own function
       //var somevalue = $(this).attr('id'); 
       });
      });

Upvotes: 0

t.niese
t.niese

Reputation: 40882

prev() is a sibling selector, so you need to be on the same level in the dom as the input element.

The first thing you will do is to use closest() to get the ancestor with class dropdown-wrapper (you could also use parent() in this case but closest is more flexible in case you change your dom structure). And on that result, you will call your prev

$('.selectable').click(function(){
  $(this).closest('.dropdown-wrapper').prev('.selected').val('hit');
});

Upvotes: 2

Johannes
Johannes

Reputation: 67778

The next-to-last line in the JS code should be:

 $(this).parent().prev('.selected').val('hit');

(You want to address the previous parent from what I understood)

https://jsfiddle.net/o7s1xgdj/

Upvotes: 0

Related Questions