Home > Software design >  JQuery Css Formatting leaks to other document elements
JQuery Css Formatting leaks to other document elements

Time:12-19

As the title says i am new to Web Development and i tried out JQuery and i came across this issue. I am specifying on my code that the element with id #btn1 enables the specific characteristic i write it to and it does that only to elements with id #p1,#p2,#p3. Why do the changes leak to other elements of p?

I expected this to format only the elements with ids(p1,p2,p3) but it formats the other p elements too.

<script>
$(document).ready(function(){
  $("button").click(function(){
    $("p").css("background-color", "yellow");
  });

  $("#btn1").click(function(){
    $("#p1,#p2,#p3").css({"background-color": "yellow", "font-size": "200%"}); // 
  });
});
</script>
<body>

<h2>This is a heading</h2>

<p style="background-color:#ff0000">This is a paragraph.</p>
<p style="background-color:#00ff00">This is a paragraph.</p>
<p style="background-color:#0000ff">This is a paragraph.</p>

<p>This is a paragraph.</p>

<button>Set background-color of p</button>

<br><hr><br>

<div id="div1">  

    <h2>This is a heading</h2>


<p id="p1" style="background-color:#ff0000">This is a paragraph.</p>
<p id="p2" style="background-color:#00ff00">This is a paragraph.</p>
<p id="p3" style="background-color:#0000ff">This is a paragraph.</p>

<p>This is a paragraph.</p>

<button id="btn1">Set multiple styles for p</button>

</div>

</body>

CodePudding user response:

Its because of this line here:

$("button").click(function(){
  $("p").css("background-color", "yellow");
});

This line adds a click event listener to every button on the page. So when you click any button, every "p" element on the page gets the background-color set to yellow

  • Related