Home  >  jQuery

Example of .addBack() in jQuery

February 17, 2013
.addBack() adds DOM element in the stack. In the current set of element .addBack() adds the previous element. Now take the example. We have three p element. Only one p has class attribute. What we are targetting is give a back ground color to all the three p with .addBack().
<p class="a">A</p>
<p>B</p>
<p>C</p>
 
We need to do first
$('p.a').nextAll().css('background-color', 'yellow')
 
The above line will give background color only for B and C because of .nextAll(). Now add the .addBack(). It will add A also in the stack.
$('p.a').nextAll().addBack().css('background-color', 'yellow')
 
Find the complete example.

 <!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<p class="a">A</p>
<p>B</p>
<p>C</p>
<script>
$('p.a').nextAll().addBack()
.css('background-color', 'yellow');
</script>
</body>
</html>
Output will look like

A

B

C

FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us