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.
Previous: Create a paragraph element with some text and append it to the end of the document body using jQuery.
Next: Using jQuery add the class " w3r_font_color " to the last paragraph element.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/jquery-exercises/1/jquery-fundamental-exercise-4.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics