Get the div index value

I am stuck with a problem here, please help. What my requirement is to get the index value for a div click. You have 2 lists, and I need to call the doSomething () function; only when the user clicks the first set of divs. In any case, I can achieve this.

Scripts and HTML are as follows

$(document).ready(function() {
 $(".list-wrapper li").click(function() {
    var index = $(".list-wrapper div").index(this);
    alert(index);
    });
});

<div class="list-wrapper">
<ul>
<li>List 1</li>
<li>List 2</li>
<li>List 3</li>
</ul>
</div>

<div class="list-wrapper">
<ul>
<li>List 1</li>
<li>List 2</li>
<li>List 3</li>
</ul>
</div>

Please, help...

+3
source share
4 answers

jQuery has powerful selectors , so usually you do not need to check the index after the event. For example:

For the first div on your page:

$(".list-wrapper:first").click(doSomething);

For the first <li>in each list:

$(".list-wrapper li:first-child").click(doSomething);

, div li. , .list-wrapper div - div list-wrapper. :

var parent = $(this).closest('div')
var index = $(".list-wrapper").index(parent);
+3

, :

http://api.jquery.com/first-selector/

$("div.list-wrapper:first").find("li").click(function() {...
+1

There are many ways to do this:

$('div.list-wrapper').first().click(function() { doSomething(); });

and

$("div.list-wrapper:first").click(function() { doSomething(); });

and

$('div.list-wrapper').eq(0).click(function() { doSomething(); });

- the first ones that come to mind. Pro-tip, enter the element type before the class for speed (div.blah is faster than .blah)

Or just get the index:

var index = $('div.list-wrapper').index(this);

replace 'this' with the parent for specificity

+1
source

Try the following:

<ul><li id="foo">foo</li><li id="bar">bar</li><li id="baz">baz</li></ul>


var listItem = document.getElementById('bar');
alert('Index: ' + $('li').index(listItem));

See this for more information: http://api.jquery.com/index/

0
source

Source: https://habr.com/ru/post/1729890/


All Articles