Search code examples
javascriptjqueryloopsjquery-selectors

jQuery how to loop through more than 1 sibling element


I have a jQuery project where I have to loop through a list of h2 headers but in each h2 header I have to loop through their siblings. Each header has more than 1 siblings. Right now I only know how to go to 1 sibling which is using the .next() function. Can someone please help me loop through a list of siblings without changing the direction of my initial code.

<script>
// Code Option 1
    function putSiblingsInTableForEachH2() {
        // line above sets function that will ultimately store siblings of each h2.toggler into a HTML table
        var siblingsGoInTable = [];
        // line creates empty array that will hold elements that will eventually go into HTML table
        var togglerHeaders = $("h2.toggler");
        // line above sets variable togglerHeaders to all h2 elements with a class of ".toggler"
        for (i = 0; i < togglerHeaders.length; i++) {
            // line above is a for loop that loops through variable togglerHeaders (for its entire length)
            var currentH2Element = togglerHeaders[i];
            // line above sets variable currentH2Element to togglerHeaders at position i
            // so when i starts at 0 currentH2Element is set to the first element in togglerHeaders which is the first h2.toggler
            for (j = 0; j < currentH2Element.nextAll(); j++) {
                if (currentH2Element.nextAll() !== currentH2Element.val()) {
                    $(siblingsGoInTable).wrapAll("<table></table>");
                } // line ends if statement
            } // line above closes for loop 
        } // line ends for loop
    } // line ends function
    putSiblingsInTableForEachH2();
    // line above actually runs function
</script>

Solution

  • You could using the .siblings() method to achieve this.

    So, something along these lines might work for you:

    <script>
        function putSiblingsInTableForEachH2() {
            var siblingsGoInTable = [];
    
            var togglerHeaders = $("h2.toggler");
    
            for (var i = 0; i < togglerHeaders.length; i++) {
    
                var currentH2Element = togglerHeaders[i];
    
                // Access siblings like this
                var siblings = $(currentH2Element).siblings();
    
                for (var j = 0; j < siblings.length; j++) {
    
                    var siblingToH2 = siblings[j];
                    // Do what you need to do with sibling element here
                }
            }
        }
    
        putSiblingsInTableForEachH2();
    
    </script>