Open In App

JQuery | Change the text of a span element

Given an HTML document and the task is to change the text content of a <span> element. There are various methods used to change the span elements which are discussed below:

Example 1: This example changes the content by using JQuery’s text() method .




<!DOCTYPE HTML> 
<html
    <head
        <title
            JQuery | Change the text of a span element
        </title>
          
        <script src
        </script>
    </head
      
    <body style = "text-align:center;" id = "body"
          
        <h1 style = "color:green;"
            GeeksForGeeks 
        </h1
          
        <span id="GFG_Span" style = "font-size: 15px; font-weight: bold;"
            This is text of Span element. 
        </span>
          
        <br><br>
          
        <button
            Change
        </button>
          
        <p id = "GFG_DOWN" style
            "color:green; font-size: 20px; font-weight: bold;">
        </p>
          
        <script>
            $('button').on('click', function() {
                $('#GFG_Span').text("New Span text content");
                $('#GFG_DOWN').text("Span content changed");
            });     
        </script
    </body
</html>                    

Output:

Example 2: This example changes the content by using JQuery’s html() method .




<!DOCTYPE HTML> 
<html
    <head
        <title
            JQuery | Change the text of a span element
        </title>
          
        <script src
        </script>
    </head
      
    <body style = "text-align:center;" id = "body"
          
        <h1 style = "color:green;"
            GeeksForGeeks 
        </h1
          
        <span id="GFG_Span" style = "font-size: 15px; font-weight: bold;">
             This is text of Span element. 
        </span>
          
        <br><br>
          
        <button
            Change
        </button>
          
        <p id = "GFG_DOWN" style
            "color:green; font-size: 20px; font-weight: bold;">
        </p>
          
        <script>
            $('button').on('click', function() {
                $('#GFG_Span').html("<p>New Span text content</p>");
                $('#GFG_DOWN').text("Span content changed");
            });     
        </script
    </body
</html>                    

Output:


Article Tags :