Home  >  Article  >  Web Front-end  >  Why Does `:last-of-type` Fail to Select the Last Element with a Specific Class?

Why Does `:last-of-type` Fail to Select the Last Element with a Specific Class?

Barbara Streisand
Barbara StreisandOriginal
2024-10-27 05:47:29379browse

Why Does `:last-of-type` Fail to Select the Last Element with a Specific Class?

Why :last-of-type Selects Incorrectly with a Class Attribute

In the provided HTML and CSS code, it is intended for only the last element with the class "visible" within a div to be displayed. However, the .class:last-of-type selector remains ineffective.

The issue arises from a misconception of :last-of-type's function. While it accurately selects the last element of a particular type (in this case,

elements), it does not consider specific class attributes.

Pseudo-Class Functionality:

The W3C defines :last-of-type as: "An element that is the last sibling of its type." Its behavior can be summarized as follows:

  1. It identifies elements within each containing element in the HTML.
  2. It locates the last element in each set of identified elements.
  3. It verifies if the selected element is a

    element.

  4. It checks for the presence of the ".visible" class attribute.

Selector Analysis:

The selector p.visible:last-of-type targets the following:

  • Identifies all

    elements within each div.

  • Selects the last

    element in each set.

  • Requires both the last

    element and the ".visible" class attribute.

Result:

Since only the first two

elements have the ".visible" class, none of the

elements become visible despite using :last-of-type correctly.

Solution:

To select the last element with the ".visible" class, a different approach is necessary. JavaScript or a custom CSS attribute-based solution may provide a suitable workaround.

The above is the detailed content of Why Does `:last-of-type` Fail to Select the Last Element with a Specific Class?. 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