master2080 master2080 - 3 months ago 6
CSS Question

Find out which element was clicked from the list of elements

I have a few divs that share the same class.
I have a dropdown that changes the background color of one of those divs when selected(option 2 changes div #2).

My question is how can I change the dropdown option when clicking a certain div?

I have the logic behind changing the actual option and the div clicks, but I can't figure out how to find exactly which of the divs was clicked(the divs are dynamically created, so they don't have Ids, only class names).

Is there any way to check what div was clicked relatively to the entire list of divs with the same class?
Thanks.

Example code:

<select class="size form-control" id="size" name="size">
<option value="1">first div</option>
<option value="2">second div</option>
<option value="4">third div..</option>
</select>

<div class="collection">random</div>
<div class="collection">text</div>
<div class="collection">inside</div>
<div class="collection">here</div>


Edit:

What I have:

The select can change the color of a div depending on choice.

Clicking a div changes it's own color.

What I need:

Clicking a div also changes the option in the select.
I hope it's a bit clearer now

Kld Kld
Answer

With jQuery You can get the index of the clicked div by using .index()

$('div.collection').click(function(){
var index = $('div.collection').index($(this));
  console.log(index);
  
  $('select').val(index+1);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="collection">Div1</div>
<div class="collection">Div2</div>
<div class="collection">Div3</div>
<div class="collection">Div4</div>



<select class="size form-control" id="size" name="size">
<option value="1">first div</option>
<option value="2">second div</option>
<option value="4">third div..</option>
</select>

Comments