jQuery - 元素類選擇器



描述

元素類選擇器選擇所有與元素給定類匹配的元素。

語法

以下是使用此選擇器的簡單語法:

$('.classid')

引數

以下是此選擇器使用到的所有引數的描述:

  • classid − 這是文件中可用的類ID。

返回值

與任何其他 jQuery 選擇器一樣,此選擇器也返回一個包含已找到元素的陣列。

示例

  • $('.big') − 選擇所有具有給定類ID big 的元素。

  • $('p.small') − 選擇所有具有給定類ID small 的段落。

  • $('.big.small') − 選擇所有同時具有類 bigsmall 的元素。

以下示例將選擇所有具有類 .big 的 div 元素,並將其背景色設定為黃色:

<html>
   <head>
      <title>The Selecter Example</title>
      <script type = "text/javascript" 
         src = "https://tutorialspoint.tw/jquery/jquery-3.6.0.js">
      </script>
   
      <script type = "text/javascript" language = "javascript">
         $(document).ready(function() {
            /* This would select second division only*/
            $(".big").css("background-color", "yellow");
         });
      </script>
   </head>
	
   <body>
      <div class = "big" id="div1">
         <p>This is first division of the DOM.</p>
      </div>

      <div class = "medium" id = "div2">
         <p>This is second division of the DOM.</p>
      </div>

      <div class = "small" id = "div3">
         <p>This is third division of the DOM</p>
      </div>
   </body>
</html>

這將產生以下結果:

jquery-selectors.htm
廣告
© . All rights reserved.