w3resource logo
jquery exercises

jQuery: Set the background color red of the specified elements

jQuery Fundamental - I : Exercise-2

Set the background color red of the following elements using jQuery.


jQuery
Exercises

Sample solution :

HTML Code :

<!DOCTYPE html>
  <html>
  <head>
  <script src="https://code.jquery.com/jquery-git.js"></script>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Set the background color red of the following elements using jQuery.</title>
  <style type="text/css">
  button {
  display: block;
  margin: 20px 0 0 0;
  }   </style>
</head>
  <body>
  <textarea>TutoRIAL</textarea> 
  <p>jQuery</p>
  <span>Exercises</span>
  <button id="button1">Click to see the effect</button>
  </body>
  </html>

JavaScript Code:

$('#button1').click(function(){ 
$("p").add( "span" ).add("textarea").css( "background", "red" );
});

Used Methods :

  • .add(elements) : Create a new jQuery object with elements added to the set of matched elements. Here .add() method adds more elements like "span", "textarea" etc.
  • .css(propertyName) : Get the computed style properties for the first element in the set of matched elements.

See the Pen jquery-fundamental-exercise-2 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus