Find all the text nodes inside a <div> element and wrap them with a <b> element:
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ $("div").contents().filter("em").wrap("<b/>"); });/*from ww w. j a va2s . c o m*/ }); </script> </head> <body> <div><em>Hello world!</em></div> <button>test</button><br> </body> </html>
The contents()
method returns all direct children, including text and comment nodes.
A text node is the actual text displayed by an element.
$(selector).contents()