如何用jQuery找到一个元素的文本

如何用jQuery找到一个元素的文本

我们将学习如何使用jQuery的API来寻找一个元素。这篇文章需要一些HTMLCSSJavaScript、Bootstrap和jQuery的知识。可以根据元素是否包含我们想找的字符串来选择元素。这可以使用jQuery的包含选择器来选择包含该字符串的元素。

关于包含选择器

根据元素的不同,匹配的文本可以直接出现在所选元素的内部或其后代。jQuery中的:contains() 选择器是用来选择包含指定字符串的元素。该文本必须有一个匹配的案例才能被选中。

语法:一串要查找的文本。它是区分大小写的。

jQuery(":contains(text)")
JavaScript

步骤:

  • 在你的本地系统中创建一个HTML文件” index.html”。
  • 遵循基本的HTML模板和两段式,将文本添加到 <p>标签。
  • 选择 <p>标签,并将你要选择的关键词作为参数传给contains selector方法。
  • 在你成功地完成上述步骤后,为所选段落附加一个CSS属性,其中包含你在contains方法中作为参数传递的关键字。

例子:在这种情况下,我们要找的是包含 “Gfg “这个词的元素。选择元素后,我们改变包含 “Gfg “这个词的特定段落的颜色。

<!DOCTYPE html>
<html>
  
<head>
    <link href=
"https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css"
        rel="stylesheet" integrity=
"sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC"
        crossorigin="anonymous">
      
    <script src=
"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js">
    </script>
  
    <style>
        body {
            border: 2px solid green;
            min-height: 240px;
        }
  
        .center {
            display: flex;
            justify-content: center;
        }
  
        h1 {
            color: green;
            text-align: center;
        }
    </style>
</head>
  
<body>
    <h1>GeeksforGeeks</h1>
  
    <div class="row container">
        <div class="col">
            <p>
                Web development refers to the building, 
                creating, and maintaining of websites.
                Gfg includes aspects such as web design,
                web publishing, web programming, and 
                database management. It is the creation 
                of an application that works over the 
                internet i.e. websites.
            </p>
        </div>
          
        <div class="col">
            <p>
                Web development refers to the building, 
                creating, and maintaining of websites.
                It includes aspects such as web design, 
                web publishing, web programming, and 
                database management. It is the creation 
                of an application that works over the 
                internet i.e. websites.
            </p>
        </div>
    </div>
  
    <script>
        $('p:contains("Gfg")').css({ 'color': 'green' });
    </script>
</body>
  
</html>
HTML

输出:

如何用jQuery找到一个元素的文本?

contains text

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

jQuery 方法

登录

注册