Home > Web Front-end > CSS Tutorial > Why Doesn\'t `h3:nth-child(1):contains(\'a\')` Select the First Containing \'a\'?

Why Doesn\'t `h3:nth-child(1):contains(\'a\')` Select the First Containing \'a\'?

Susan Sarandon
Release: 2024-12-10 08:56:13
Original
773 people have browsed it

Why Doesn't `h3:nth-child(1):contains('a')` Select the First  Containing

Why Does h3:nth-child(1):contains('a') Fail?

In an attempt to select the first h3 element that contains the text "a," the selector h3:nth-child(1):contains('a') is being used. However, this selector does not yield the desired result.

Explanation:

The CSS3 selector :contains() was never implemented as a standard and thus is not supported in major browsers. This selector was intended to match elements that contained specific text, but its implementation would have led to performance issues due to matching all ancestors of the element as well.

Alternative Solutions:

Since :contains() is not available, an alternative approach is required:

  • Modify the HTML: Rearrange the HTML structure to place the desired h3 element in a distinct location.
  • Use jQuery: jQuery provides its own :contains() selector, which can be used as follows:
$("h3:first").filter(function() {
  return $(this).text().indexOf("a") >= 0;
});
Copy after login

Considerations:

  • For jQuery and Selenium RC, :contains() is supported but can lead to unexpected selections due to matching ancestors.
  • CSS2 selector h3:first-child can be used instead of h3:nth-child(1) for better browser support.

The above is the detailed content of Why Doesn\'t `h3:nth-child(1):contains(\'a\')` Select the First Containing \'a\'?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template