How does the all selector ("*") work in jQuery?

Viewed 60

I was going through the jQuery documentation and I was really confused by the all selector ("*") example. Why does the 'h3' tag in this example get the red border? Here is the official documentation.

var elementCount = $( "*" ).css( "border", "3px solid red" ).length;
$( "body" ).prepend( "<h3>" + elementCount + " elements found</h3>" );
h3 {
  margin: 0;
}

div, span, p {
  width: 80px;
  height: 40px;
  float: left;
  padding: 10px;
  margin: 10px;
  background-color: #EEEEEE;
}
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>all demo</title>
    <script src="https://code.jquery.com/jquery-3.4.1.js"></script>
  </head>
  <body>
    <div>DIV</div>
    <span>SPAN</span>
    <p>P <button>Button</button></p>
  </body>
</html>

Since the prepend statement is executed after the first one, I was expecting the h3 tag to have no red border.

I inspected the h3 element using browser tools and it does not show me any red border in its style either.

1 Answers

* selects all elements in the DOM. This includes the <body>, and that is what the border you're seeing is actually around. It'll be more obvious if you remove the float, everything else is the same in the below snippet:

var elementCount = $("*").css("border", "3px solid red").length;
$("body").prepend("<h3>" + elementCount + " elements found</h3>");
h3 {
  margin: 0;
}

div,
span,
p {
  width: 80px;
  height: 40px;
  padding: 10px;
  margin: 10px;
  background-color: #EEEEEE;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>DIV</div>
<span>SPAN</span>
<p>P <button>Button</button></p>

Float elements do not result in their containers expanding to fit. When you append the h3, since it's the only non-float element inside the body, the body's border appears to be the same as the h3's border.

Similarly, if you don't append the h3, you'll see an odd thick red border on the top, which appears to surround nothing, because there are no elements taking up space in the body:

$("*").css("border", "3px solid red");
h3 {
  margin: 0;
}

div,
span,
p {
  float: left;
  width: 80px;
  height: 40px;
  padding: 10px;
  margin: 10px;
  background-color: #EEEEEE;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>DIV</div>
<span>SPAN</span>
<p>P <button>Button</button></p>

The h3 doesn't actually have a border - it just looks that way, due to the body occupying the same area.

Related