Updating element content in jQuery
We can use following jQuery methods to update content of elements in jQuery selection.
- text()
- html()
- replaceWith
- remove()
.text()
This method can be used to update the text content of the matching elements. Any markup data will be shown as text.
HTML
<p>This is a paragraph</p> <button>Click me</button>
jQuery
$(document).ready(function(){ $("button").click(function(){ $("p").text("Paraghaph contents updated"); }); });
Output
.html()
This method can be used to update the html content of matching elements.
HTML
<p>This is a paragraph</p>
CSS
.red { color: red; }
jQuery
$(document).ready(function() { $("p").html("<span class='red'><h1>Hello</h1></span>"); });
Output
.replaceWith()
This method replaces the content of any matching element. It also returns the replaced elements.
HTML
<p> Click below button to disable it : </p> <button>Button 1</button>
jQuery
$("button").click(function(){ $(this).replaceWith("<button disabled>" + $( this ).text() + " disabled </button>"); });
Output
.remove()
This method removes any matching elements.
HTML
<p> Click below buttons to remove them </p> <button>Remove me</button> <button>Remove me</button> <button>Remove me</button>
jQuery
$(document).ready(function(){ $("button").click(function(){ $(this).remove(); }); });
Output
© 2016, https:. All rights reserved. On republishing this post, you must provide link to original post