The cliche about the difference between jquery id selector and class selector

  • 2021-07-21 05:55:24
  • OfStack

Examples are as follows:


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <link href="style.css" rel="external nofollow" rel="external nofollow" rel="stylesheet" type="text/css"/>
  <script type="text/javascript" src="jquery-2.1.4.js"></script>
  <script type="text/javascript" src="dams.js">
  </script>
</head>
<body>
  <div class="box">hello</div>
  <div class="box">world</div>
</body>
</html>



$(function(){
  alert($('.box').size());  // Return 2
});

The size () method returns the number of DOM objects


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <link href="style.css" rel="external nofollow" rel="external nofollow" rel="stylesheet" type="text/css"/>
  <script type="text/javascript" src="jquery-2.1.4.js"></script>
  <script type="text/javascript" src="dams.js">
  </script>
</head>
<body>
  <div id="box">hello</div>
  <div id="box">world</div>
</body>
</html>





$(function(){
  alert($('#box').size());  // Can only be obtained 1 A id=box Adj. DOM Object that returns the 1
});

That is, id is only 1, and even if there are multiple elements of the same id, the jquery selector can only get one of them. So: If you want to set an action on id in jquery, id is only allowed to appear once in the page.

For the CSS style, you can select all id=box DOM objects on the page:


#box {

  color: red;


};

The jQuery selector is written in a similar way to the CSS selector, but has different functions:

CSS adds a single 1 style when it finds an element, while jquery adds an action behavior.


Related articles: