w3resource

jQuery: Remove all paragraphs from the DOM

jQuery Fundamental - II : Exercise-78

Remove all paragraphs from the DOM.

Note: .detach() is used to remove the set of matched elements from the DOM.

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>Remove all paragraphs from the DOM.</title>
</head>
<body>
<ul>
<li>Exercises</li>
</ul>
<p>jQuery</p>
<p>JavaScript</p>
<button>Attach/detach paragraphs</button>
</body>
</html>

CSS Code :

p {
background: orange;
margin: 6px 0;
}
p.off {
background: black;
}

JavaScript Code :

$( "p" ).click(function() {
$( this ).toggleClass( "off" );
});
var p;
$( "button" ).click(function() {
  if ( p ) {
p.appendTo( "body" );
p = null;
} else {
p = $( "p" ).detach();
}
});

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


Contribute your code and comments through Disqus.

Previous: Find all inputs that are descendants of a form and mark them with a dotted red border. Give a green background to inputs that are descendants of a fieldset that is a descendant of a form.
Next: Find all elements that are disabled.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

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/2/jquery-fundamental-exercise-78.php