Home >Web Front-end >CSS Tutorial >How Can I Select the Last Visible Div Using CSS and JavaScript?

How Can I Select the Last Visible Div Using CSS and JavaScript?

Linda Hamilton
Linda HamiltonOriginal
2024-11-30 11:29:13874browse

How Can I Select the Last Visible Div Using CSS and JavaScript?

Selecting the Last Visible div with CSS

In CSS, it is not natively possible to target a specific visible element using a selector alone. A technique known as :visible is not sufficient in this context as it encompasses all visible elements, without distinguishing between the last visible element or otherwise.

To overcome this limitation and select the last visible div, one must consider alternative approaches, such as manipulating styles and leveraging JavaScript or jQuery.

JavaScript and jQuery Approach

Utilizing JavaScript or jQuery, one can achieve this selection as follows:

  • Use the :visible selector to target visible divs.
  • Employ the last() method to obtain the last visible div.
var last_visible_element = $('div:visible:last');

If the visible divs possess a specific class or ID, refine the selector accordingly:

var last_visible_element = $('#some-wrapper div:visible:last');

The above is the detailed content of How Can I Select the Last Visible Div Using CSS and JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn