Peterson Peterson - 2 months ago 8
CSS Question

jQuery CSS Selector issue

In the following code, after the jQuery runs, I expected only 2 to be seen with background red.

However, after jQuery runs, I can see 1, 2 and 3 with their backgrounds red.

Where is the glitch?

HTML

<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('div').css('display','block').css('background','red');
});
</script>
</head>
<body>
<div style="display:none">1</div>
<div style="display:block">2</div>
<div style="display:none">3</div>
</body>
</html>


Output

enter image description here

Answer

.css('display','block') is not a selector, it's a setter. You set display: block to all divs and then set a red background to all too. It's called a chain.

$('div')     .css('display','block').css('background','red');
//^ selector  ^ first setter         ^ second setter

There are plenty of ways to select the correct div.

$("div:visible").css({display: "block", background: "red"});
$("div").filter(":visible").css({display: "block", background: "red"});
$("div[style='display:block']").css({display: "block", background: "red"});
$("div:eq(1)").css("display", "block").css({display: "block", background: "red"});
$("div").eq(1).css("display", "block").css({display: "block", background: "red"});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div style="display:none">1</div>
<div style="display:block">2</div>
<div style="display:none">3</div>