w3resource
jquery exercises

jQuery: Add the previous set of elements on the stack to the current set

jQuery Fundamental - I : Exercise-4

Using jQuery add the previous set of elements on the stack to the current set.

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>Using jQuery add the previous set of elements on the stack to the current set.</title>
</head>
<body>
<div class="left">
<p><strong>Before <code>addBack()</code></strong></p>
<div class="before-addback">
<p>JavaScript</p>
<p>jQuery</p>
</div>
</div>
<div class="right">
<p><strong>After <code>addBack()</code></strong></p>
<div class="after-addback">
<p>JavaScript</p>
<p>jQuery</p>
</div>
</div>
</body>
</html>

CSS Code:

p, div {
    margin: 5px;
    padding: 5px;
    color: #c03199;
  }
  .border {
    border: 2px solid #360e9b;
  }
  .background {
    background: #cdc8b1;
  }
  .left, .right {
    width: 40%;
    float: left;
  }
  .right {
    margin-left: 2%;
  }

JavaScript Code :

$( "div.left, div.right" ).find( "div, div > p" ).addClass( "border" );
 
// First Part
$( "div.before-addback" ).find( "p" ).addClass( "background" );
 
// Second Part
$( "div.after-addback" ).find( "p" ).addBack().addClass( "background" );

Used Methods :

  • .addClass() : Adds the specified class(es) to each element in the set of matched elements.
  • .addBack() : Add the previous set of elements on the stack to the current set, optionally filtered by a selector.

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


Contribute your code and comments through Disqus.


ankara escort
kızılay escort