Home > Article > Web Front-end > How to Exclude Hidden Elements from nth-child Selectors in jQuery?
How to Ignore Hidden Elements When Using nth-Child Selectors
In the scenario described in the original query, where hidden elements are causing issues with nth-child selectors, there are two main approaches to resolve the problem:
1. Exclude Hidden Elements from the DOM
Using jQuery, you can remove the hidden elements from the DOM entirely using the .remove() method. This ensures that they are no longer considered siblings by the nth-child selector. However, if you later wish to restore the hidden elements, this approach is not suitable.
2. Use jQuery's detach() Method
The .detach() method in jQuery detaches hidden elements from the DOM, but unlike .remove(), it maintains the element's jQuery data. This allows the detached elements to be re-inserted later without losing their data.
Updated jQuery Code:
var divs; $('.photos-board-item').each(function (i) { $(this).data('initial-index', i); }); $('.hide-others').on('click', function () { if (divs) { $(divs) .appendTo('.row') .each(function () { var oldIndex = $(this).data('initial-index'); $('.photos-board-item').eq(oldIndex).before(this); }); divs = null; } else { divs = $('.css--all-photo').detach(); } });
Explanation:
Note:
The above is the detailed content of How to Exclude Hidden Elements from nth-child Selectors in jQuery?. For more information, please follow other related articles on the PHP Chinese website!