📜  如何从 jQuery 选择器获取 DOM 元素?

📅  最后修改于: 2022-05-13 01:56:01.900000             🧑  作者: Mango

如何从 jQuery 选择器获取 DOM 元素?

文档对象模型 (DOM)元素类似于 HTML 页面上的 DIV、HTML、BODY 元素。 jQuery 选择器用于使用 jQuery 选择一个或多个 HTML 元素。大多数情况下,我们使用选择器来访问 DOM 元素。如果它们只是 HTML 页面中的一个特定的唯一元素,我们可以通过它的标签作为$(“tag”)来访问它,但是当我们有多个这样的元素时,我们将使用当 $(“ #id”)开始发挥作用。

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

句法

$(“selector”).get(0)


或者

$(“selector”)[0]


下面的示例说明了该方法。



示例 1:此示例将使用$(“selector”).get(0):

Javascript


 

    The jQuery DOM elements Example
     
    
 
    

 

 
    
        

Hello

                  

GeeksforGeeks

                  

            A Computer Science Portal for Geeks         

                  
            Enter name:                      
        
                           
                   

            Clicking button will Resets the             textbox and changes the background             colors of the above texts.         

      
 


Javascript


 

    The jQuery Example
 
    
 
    

 

    
        
            

Hello Welcome to GeeksforGeeks

                                       
                          

                The above button changes the                 content of the above text.             

        
    
 


输出:由于 reset() 方法在 jquery 中不可用,我们已将 jquery 元素转换为 javascript 对象或原始 DOM 元素。

示例 2:此示例将说明$(“selector”)[0]选择器的使用。

Javascript



 

    The jQuery Example
 
    
 
    

 

    
        
            

Hello Welcome to GeeksforGeeks

                                       
                          

                The above button changes the                 content of the above text.             

        
    
 

输出:

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