Open In App

How to replace text after a nested tag in jQuery ?

Last Updated : 03 Mar, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will see how to replace text after a nested tag using jQuery. There is one main approach that can be followed.

Approach: We use the click(), contents() and filter() methods and this, nodeType and nodeValue properties. There is one division element with an id of outer-tag with a span tag with a class of nested-tag nested within it. A button is also defined which replaces the text after the nested tag on click. We attach a click event to the button using the click() method. 

This method contains an anonymous function to execute on button click. We select the div element and we get all its children nodes including any text nodes using the contents() method. 

Next, we filter through all these children nodes which are text nodes using the filter() method. Simply check for the node type of each children node using the nodeType property. If the nodeType property returns the value of 3, then the given node is a text node. Now, to get the text after the nested tag, we select the second text node out of all the filtered text nodes by indexing (index 1). To replace the text value of the selected text node, we use the nodeValue property which helps us set the new value of the text node.

Example: In this particular example, the original text after the nested tag is ” C.S hub for geeks.”. We replace this text with ” Computer Science portal for geeks.” using the approach discussed above.

HTML




<!DOCTYPE html>
<html>
  
<head>
    <script src=
    </script>
  
    <!-- Basic inline styling -->
    <style>
        body {
            text-align: center;
        }
  
        button {
            margin-top: 2rem;
            cursor: pointer;
        }
    </style>
</head>
  
<body>
    <h2 style="color:green">GeeksforGeeks</h2>
    <p>jQuery - Replace text after a nested tag</p>
      
    <div id="outer-tag">
        <span class="nested-tag">
            GeeksforGeeks is a </span> C.S. hub for geeks.
    </div>
    <button>Click me to change text after nested tag</button>
    <script type="text/javascript">
  
        $("button").click(function () {
            $("#outer-tag").contents().filter(function () {
                return this.nodeType == 3;
            })[1].nodeValue = "Computer Science portal for geeks.";
        });
    </script>
</body>
  
</html>


Output:



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads