Selectors-Content Filter

 

一、:contains() Selector

指定的元素中,選出指定的文字。

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <script src="https://code.jquery.com/jquery-3.0.0.js"></script>
    <meta name="viewport" content="width=device-width">
</head>
<body>
    <div>
        <p>aaa</p>
        <p>bbb</p>
        <span>ccc</span>
    </div>

    <div>
        <p>aaa</p>
        <span>bbb</span>
        <span>ccc</span>
        <p>ddd</p>
    </div>

    <script>
        $("p:contains(bbb)").css("color", "red");
    </script>
</body>
</html>

 

二、:empty Selector

找出父元素底下沒有子元素(空白節點與文字節點也算)的jQuery object

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <script src="https://code.jquery.com/jquery-3.0.0.js"></script>
    <meta name="viewport" content="width=device-width">
    <style>
        div {
            width: 100px;
            height: 100px;
            background-color: yellow;
        }
    </style>
</head>
<body>
    <div>
        <p>aaa</p>
        <p>bbb</p>
        <span>ccc</span>
    </div>

    <div>
        <p>aaa</p>
        <span>bbb</span>
        <span>ccc</span>
        <p>ddd</p>
    </div>
    <div></div>
    <div>
    </div>

    <script>
        $("div:empty").css("background-color", "red");
    </script>
</body>
</html>

 

三、:has() Selector

找出指定元素底下是否擁有某元素。

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>has demo</title>
    <style>
        .test {
            border: 3px inset red;
        }
    </style>
    <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>

    <div><p>Hello in a paragraph</p></div>
    <div>Hello again! (with no paragraph)</div>

    <script>
        $("div:has(p)").addClass("test");
    </script>

</body>
</html>

 

四、:parent Selector

找出父元素底下至少擁有一個子元素(空白節點與文字節點也算)的jQuery object,

注意,這特性剛好與:empty相反。

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <script src="https://code.jquery.com/jquery-3.0.0.js"></script>
    <meta name="viewport" content="width=device-width">
    <style>
        div {
            width: 100px;
            height: 100px;
            background-color: yellow;
        }
    </style>
</head>
<body>
    <div>
        <p>aaa</p>
        <p>bbb</p>
        <span>ccc</span>
    </div>

    <div>
        <p>aaa</p>
        <span>bbb</span>
        <span>ccc</span>
        <p>ddd</p>
    </div>
    <div></div>
    <div>
    </div>

    <script>
        $("div:parent").css("background-color", "red");
    </script>
</body>
</html>