Search code examples
jquerychildrenstring-length

Index of children in parent of a specific class


A parent container called ".content" contains various children and these children are created dynamically. I am trying not to do an each loop and compare the children with the one clicked.

This code tells me how many children of the type I have.

$(this).parents(".content").children(".r-s, .r-f").length

say an example where the above length equals 5, I need to know WHICH in either (0-4 or 1-5) children was selected.

I have been looking at jquery .filter() hoping for an answer, .is() also seems promising. Any suggestions?


Solution

  • You could use the index function of jQuery to get the position of the clicked element inside the parent's element. Sth. like this should work:

    function clickCallback(event) {
      var index = $(".r-s, .r-f").index(event.target);
    }
    

    Alternatively, if you create the elements dynamically, you could add an attribute to the elements with there respecitve index and then simply access that in your click callback.

    function clickCallback(event) {
      var index = event.target.getAttribute("customIndex");
    }