📌  相关文章
📜  如何在 jQuery 中按属性选择元素?

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

如何在 jQuery 中按属性选择元素?

jQuery 是一个轻量级的 JavaScript 库。在原生 JavaScript 语言中,getElementById 方法用于选择元素。然而,jQuery 为相同的目的提供了一个更轻量的替代方案。 'jQuery Selector' 允许用户操作 HTML 元素和其中的数据(DOM 操作)。

句法

$("[attribute=value]")

在这里,属性和值是必需的。

一些最常用的 jQuery 选择器

SyntaxExampleSelection
*$(“*”)All elements on the webpage
#id$(“#geeks”)Elements with id=”geeks”.class$(“.geeks”)All elements with class=”geeks”:first$(“p:first”)First ‘p’ element of the webpage:header$(“:header”)All the header elements like h1, h2, h3, h4 etc:empty$(“:empty”)All the empty elements:input$(“:input”)All the input elements like text, password etc:text$(“:text”)Input elements with type=”text”:last-child$(“p:last-child”)Those ‘p’ elements that are the last child of their parents:animated$(“:animated”)All the animated elements on the webpage

#id 选择器: #id 选择器指定要选择的元素的 id。它不应以数字开头,并且 id 属性在文档中必须是唯一的,这意味着它只能使用一次。



句法:

$("#example")

仅当用户想要查找唯一元素时才必须使用 id 选择器。

例子:



      

    
        How to select elements from
        attribute in jQuery ?
    
      
    
          
    

  

    

GeeksforGeeks

        

This is a constant paragraph.

           

        This paragraph will get hidden once         the button is clicked.     

           

输出:

  • 点击按钮前:
  • 点击按钮后:

.class 选择器: .class 选择器指定要选择的元素的类。它不应以数字开头。它为多个 HTML 元素提供样式。

$(".example")

例子:



      

    
  
    

  

    

GeeksForGeeks

        

This is a paragraph.

    

This is another paragraph.

           

输出:

  • 点击按钮前:
  • 点击按钮后:

:first Selector:它是一个jQuery Selector,用于选择指定类型的第一个元素。

句法:

$(":first")

例子:

 
 
  
 
    jQuery :first selector
      
     
      
     
 
  
 
    

GeeksforGeeks

    

jQuery

      

JavaScript

      

PHP

        

输出: