如何从jQuery选择器中获得一个DOM元素

如何从jQuery选择器中获得一个DOM元素

文档对象模型(DOM)元素是像HTML页面上的DIV,HTML,BODY元素。一个jQuery选择器是用来使用jQuery选择一个或多个HTML元素。大多数情况下,我们使用选择器来访问DOM元素。如果他们在HTML页面中只有一个特殊的元素,我们可以通过它的标签(“tag”)来访问它,但当我们有多个同类元素时,我们将通过ID来访问它们,这时(“#id”)就发挥作用了。

但是如果我们想使用原始的DOM元素,那么我们可以把它们转换成javascript对象,这样我们就可以把它们用于javascript中的方法,而不是jquery中的。

语法

$(“selector”).get(0)

或者,

$(“selector”)[0]

下面的例子说明了这种方法。

例子1:这个例子将使用$(“选择器”).get(0):

<!DOCTYPE html>
<html>
 
<head>
    <title>The jQuery DOM elements Example</title>
     
    <script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
    </script>
 
    <script>
        (document).ready(function() {
 
            // Access with tag
            ("p").css("color", "red");
            ("button").click(function() {
                 
                // Access with id
                ("#d1").css("color", "purple");
                ("#d2").css("color", "green");
                ("#d3").css("color", "black");
 
                // Converting into javascript object.
                $("#d4").get(0).reset();
            });
        });
    </script>
</head>
 
<body style="text-align:center;">
 
    <div>
        <h4 id="d1">Hello</h4>
         
        <h1 id="d2">GeeksforGeeks</h1>
         
        <h3 id="d3">
            A Computer Science Portal for Geeks
        </h3>
         
        <form id="d4">
            Enter name:
            <input type="text" />
        </form>
        <br>
         
        <button>Button</button>
        <br>
         
         
<p>
            Clicking button will Resets the
            textbox and changes the background
            colors of the above texts.
        </p>
 
    </div>
</body>
 
</html>

输出:由于在jquery中没有reset()方法,我们把jquery元素转换成javascript对象或原始DOM元素。

如何从jQuery选择器中获得一个DOM元素?

例子2:这个例子将说明$(“选择器”)[0]选择器的使用。

<!DOCTYPE html>
<html>
 
<head>
    <title>The jQuery Example</title>
 
    <script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
    </script>
 
    <script>
        (document).ready(function() {
 
            // Access with tag
            ("h1").css("color", "green");
            ("button").click(function() {
 
                // d1 gets replaced with d4.
                ("#d1")[0].outerHTML =
                "<h3 id='d4'>A Computer Science Portal for Geeks</h3>";
                $("#d4").css("color", "black");
            });
        });
    </script>
</head>
 
<body>
    <center>
        <div>
            <h1 id="d1">Hello Welcome to GeeksforGeeks</h1>
             
            <button>Button</button>
            <br>
             
            <h4>
                The above button changes the
                content of the above text.
            </h4>
        </div>
    </center>
</body>
 
</html>

输出:

如何从jQuery选择器中获得一个DOM元素?

注意:由于outerHTML是一个元素的HTML,包括该元素本身在jquery中是不可用的。我们把jquery元素转换成javascript对象或原始DOM元素来访问outerHTML,并把它替换成另一个标题。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程