Как изменить текст span через js

If I have a span, say: hereismytext How do I use JavaScript to change "hereismytext" to "newtext"?

Many people still come across this question (in 2022) and the available answers are not really up to date.

Use innerText is the best method

As you can see in the MDM Docs innerText is the best way to retrieve and change the text of a <span> HTML element via Javascript.

The innerText property is VERY well supported (97.53% of all web users according to Caniuse)

How to use

Simple retrieve and set new text with the property like this:

let mySpan = document.getElementById("myspan");

console.log(mySpan.innerText);

mySpan.innerText = "Setting a new text content into the span element.";

Why better than innerHTML ?

Don’t use innerHTML to updating the content with user inputs, this can lead to major vulnerability since the string content you will set will be interpreted and converted into HTML tags.

This means users can insert script(s) into your site, this is known as XSS attacks/vulnerabilities (Cross-site scripting).

Why better than textContent ?

First point textContent isn’t supported by IE8 (but I think in 2022 nobody cares anymore).
But the main element is the true difference of result you can get using textContent instead of innerText.

The example from the MDM documentation is perfect to illustrate that, so we have the following setup:

<p id="source">
  <style>#source { color: red;  } #text { text-transform: uppercase; }</style>
<span id=text>Take a look at<br>how this text<br>is interpreted
       below.</span>
  <span style="display:none">HIDDEN TEXT</span>
</p>

If you use innerText to retrieve the text content of <p id="source"> we get:

TAKE A LOOK AT
HOW THIS TEXT
IS INTERPRETED BELOW.

This is perfectly what we wanted.

Now using textContent we get:


  #source { color: red;  } #text { text-transform: uppercase; }
Take a look athow this textis interpreted
       below.
  HIDDEN TEXT

Not exactly what you expected…

This is why using textContent isn’t the correct way.

Last point

If you goal is only to append text to a <p> or <span> HTML element, the answer from nicooo. is right you can create a new text node and append it to you existing element like this:

let mySpan = document.getElementById("myspan");

const newTextNode = document.createTextNode("Youhou!"),

mySpan.appendChild(newTextNode);

Improve Article

Save Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    Given an HTML document and the task is to change the text of the span element. There are two properties used to change the content.

    HTML DOM textContent Property: This property set/return the text content of the defined node, and all its descendants. By setting the textContent property, the child nodes the removed and replaced by a single text node having the specified string. 

    Syntax:

    • Return the text content of a node:
    node.textContent
    • Set the text content of a node:
    node.textContent = text

    HTML DOM innerText Property: This property set/return the text content of the defined node, and all its descendants. By setting the innerText property, any child nodes are removed and replaced by a single text node having the specified string. 

    Syntax:

    • Return the text content of a node:
    node.innerText
    • Set the text content of a node:
    node.innerText = text

    Example 1: This example changes the content by using textContent property

    html

    <h1 style="color:green;">

        GeeksforGeeks

    </h1>

    <span id="GFG_Span">

        This is text of Span element.

    </span>

    <br><br>

    <button onclick="gfg_Run()">

        Change

    </button>

    <p id="GFG_DOWN">

    </p>

    <script>

        var span = document.getElementById("GFG_Span");

        var el_down = document.getElementById("GFG_DOWN");

        function gfg_Run() {

            span.textContent = "New Span content";

            el_down.innerHTML = "Span content changed";

        }        

    </script>

    Output:

    JavaScript Change the text of a span element

    JavaScript Change the text of a span element

    Example 2: This example changes the content by using innerText property

    html

    <h1 style="color:green;">

        GeeksforGeeks

    </h1>

    <span id="GFG_Span">

        This is text of Span element.

    </span>

    <br><br>

    <button onclick="gfg_Run()">

        Change

    </button>

    <p id="GFG_DOWN">

    </p>

    <script>

        var span = document.getElementById("GFG_Span");

        var el_down = document.getElementById("GFG_DOWN");

        function gfg_Run() {

            span.innerText = "New Span content";

            el_down.innerHTML = "Span content changed";

        }        

    </script>

    Output:

    JavaScript Change the text of a span element

    JavaScript Change the text of a span element

    Improve Article

    Save Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    Given an HTML document and the task is to change the text of the span element. There are two properties used to change the content.

    HTML DOM textContent Property: This property set/return the text content of the defined node, and all its descendants. By setting the textContent property, the child nodes the removed and replaced by a single text node having the specified string. 

    Syntax:

    • Return the text content of a node:
    node.textContent
    • Set the text content of a node:
    node.textContent = text

    HTML DOM innerText Property: This property set/return the text content of the defined node, and all its descendants. By setting the innerText property, any child nodes are removed and replaced by a single text node having the specified string. 

    Syntax:

    • Return the text content of a node:
    node.innerText
    • Set the text content of a node:
    node.innerText = text

    Example 1: This example changes the content by using textContent property

    html

    <h1 style="color:green;">

        GeeksforGeeks

    </h1>

    <span id="GFG_Span">

        This is text of Span element.

    </span>

    <br><br>

    <button onclick="gfg_Run()">

        Change

    </button>

    <p id="GFG_DOWN">

    </p>

    <script>

        var span = document.getElementById("GFG_Span");

        var el_down = document.getElementById("GFG_DOWN");

        function gfg_Run() {

            span.textContent = "New Span content";

            el_down.innerHTML = "Span content changed";

        }        

    </script>

    Output:

    JavaScript Change the text of a span element

    JavaScript Change the text of a span element

    Example 2: This example changes the content by using innerText property

    html

    <h1 style="color:green;">

        GeeksforGeeks

    </h1>

    <span id="GFG_Span">

        This is text of Span element.

    </span>

    <br><br>

    <button onclick="gfg_Run()">

        Change

    </button>

    <p id="GFG_DOWN">

    </p>

    <script>

        var span = document.getElementById("GFG_Span");

        var el_down = document.getElementById("GFG_DOWN");

        function gfg_Run() {

            span.innerText = "New Span content";

            el_down.innerHTML = "Span content changed";

        }        

    </script>

    Output:

    JavaScript Change the text of a span element

    JavaScript Change the text of a span element

    Answer: Using textContent property

    The textContent property is used to set and return the text content of the specified node and all its descendants.

    To get the content of the span element uses the textContent property along with the getElementById() method. We can also get the content of the span element using the innerText property. Both the properties are similar, but there are some differences between them these are:

    • The textContent property returns the content of all elements while the innerText property also returns the content of all elements except <script> and <style> tag.
    • The innerText property does not display the text that is hidden using CSS properties.

    Using these properties, we can remove any number of child nodes. We can also replace the text inside the node with a single text node containing the specified node.

    Example: Using textContent Property

    In the given example, we have used the textContent property to change the text of the span element.

    <!DOCTYPE html>
    <html lang="en">
    <head>
    	<title>Change the text of a span element</title>
    </head>
    <body>
    	<span id="myspan">Hello World</span>
    	<script>
    		document.getElementById("myspan").textContent="Welcome to Studytonight";
    	</script>
    </body>
    </html>
    

    Output

    Welcome to Studytonight

    Using innerText Property

    We can also change the existing text of the span element using the JavaScript innerText property. This property sets or returns the text content of the specified element or its descendants.

    Example: Using innerText property

    In this example, we have used the innerText property to change the content of the span element.

    <!DOCTYPE html>
    <html lang="en">
    <head>
    	<title>Change the text of a span element</title>
    </head>
    <body>
    	<span id="myspan">Hello World</span>
    	<script>
        	document.getElementById("myspan").innerText="Welcome to Studytonight";  
    	</script>
    </body>
    </html>
    

    Output

    Welcome to Studytonight

    Conclusion

    Here, we have discussed how to change the text of a span element using JavaScript. We can change the text of a span element using textContent property and innerText property. Both the properties enable us to change the existing text content of the span element dynamically.



    Learn with Studytonight

    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:

    • jQuery text() Method: This method set/return the text content of specified elements. If this method is used to return content, it returns the text content of all matched elements (HTML tags will be removed). If this method is used to set content, it overwrites the content of all matched elements.

      Syntax:

      • It returns the text content.

        $(selector).text()
      • It sets the text content.

        $(selector).text(content)
      • Set text content using a function.

        $(selector).text(function(index, curContent))

      Parameters:

      • content: It is required parameter. It specifies the new text content for the selected elements.
      • function(index, curContent): It is optional parameter. It specifies the function that returns the new text content for the selected elements.
      • index: It returns the index position of element in the set.
      • curContent: It returns the current content of selected elements.
    • jQuery html() Method: This method set/return the content (HTML) of the specified elements. If this method is used to return content, it returns the content of the first matched element. If this method is used to set content, it overwrites the content of all matched elements.

      Syntax:

      • Return content

        $(selector).html()
        
      • Set content

        $(selector).html(content)
        
      • Set content using a function

        $(selector).html(function(index, curContent))
        

      Parameters:

      • content: It is required parameter. It specifies the new text content for the selected elements containing the HTML tags.
      • function(index, curContent): It is optional parameter. It specifies the function that returns the new content for the selected elements.
      • index: It returns the index position of element in the set.
      • curContent: It returns the current HTML content of selected elements.

    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:

    • Before clicking on the button:
    • After clicking on the button:

    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:

    • Before clicking on the button:
    • After clicking on the button:

    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:

    • jQuery text() Method: This method set/return the text content of specified elements. If this method is used to return content, it returns the text content of all matched elements (HTML tags will be removed). If this method is used to set content, it overwrites the content of all matched elements.

      Syntax:

      • It returns the text content.

        $(selector).text()
      • It sets the text content.

        $(selector).text(content)
      • Set text content using a function.

        $(selector).text(function(index, curContent))

      Parameters:

      • content: It is required parameter. It specifies the new text content for the selected elements.
      • function(index, curContent): It is optional parameter. It specifies the function that returns the new text content for the selected elements.
      • index: It returns the index position of element in the set.
      • curContent: It returns the current content of selected elements.
    • jQuery html() Method: This method set/return the content (HTML) of the specified elements. If this method is used to return content, it returns the content of the first matched element. If this method is used to set content, it overwrites the content of all matched elements.

      Syntax:

      • Return content

        $(selector).html()
        
      • Set content

        $(selector).html(content)
        
      • Set content using a function

        $(selector).html(function(index, curContent))
        

      Parameters:

      • content: It is required parameter. It specifies the new text content for the selected elements containing the HTML tags.
      • function(index, curContent): It is optional parameter. It specifies the function that returns the new content for the selected elements.
      • index: It returns the index position of element in the set.
      • curContent: It returns the current HTML content of selected elements.

    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:

    • Before clicking on the button:
    • After clicking on the button:

    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:

    • Before clicking on the button:
    • After clicking on the button:

    To change text in a span using jQuery, the simplest way is to use the jQuery text() method:

    $("#div1 span").text("Changed Text");

    If your span will contain html content, then you should use the jQuery html() method.

    $("#div1 span").html("Changed <strong>Text</strong>");

    Let’s say I have the following HTML:

    <div id="div1">
      <p>Today is <span>November</span> 3rd.</p>
    </div>
    

    If I want to change the text inside the span from “November” to “December”, I can use the jQuery text() method to do this with the following Javascript code.

    $("#div1 span").text("December");

    If you are using WordPress, don’t forget to change the $ to jQuery as below:

    jQuery("#div1 span").text("December");

    We can also use the jQuery html() method to change the content of a span.

    $("#div1 span").html("December");

    While the text() method is very simple, the html() method gives us the ability to insert html into our span, which gives us more options when styling the content.

    Changing the Text in a Span Using jQuery with a Click

    Many times when creating a web page and the user experience, we want to change the content of a span after an interaction with another element on the web page.

    To change the text of a span using jQuery, we can combine the text() method with a click event.

    Let’s say I have the following HTML, and I want to give the user the ability to change the text of the span from “November” to “December”.

    <div id="div1">
      <div id="click-me">Click here to update span.</div>
      <p>Today is <span>November</span> 3rd.</p>
    </div>
    

    We can utilize both the jQuery click() method and jQuery text() method to change the text from “November” to “December”.

    Below is the Javascript code which will allow the user to be able to update the text in the span:

    $("#click-me").click(function(){
        $("#div1 span").text("December");
    }); 

    The final code and output for this example of how to change the text of a span using the jQuery text() method and Javascript is below:

    Code Output:

    Click here to update span.

    Today is November 3rd.

    Full Code:

    <div class="html-code-output">
    <div id="div1">
      <div id="click-me">Click here to update span.</div>
      <p>Today is <span>November</span> 3rd.</p>
    </div>
    </div>
    
    <script>
    
    $("#click-me").click(function(){
        $("#div1 span").text("December");
    });
    
    </script>
    

    Using the html() Method to Change Text in Span

    The jQuery html() method is very useful when it comes to manipulating web pages.

    We can use the jQuery html() method to change the html and text of a span.

    Let’s say we have the following code and we want to give the user the ability to add html content to the span.

    <div id="div1">
      <div id="click-me">Click here to update span.</div>
      <p>We are going to add html to this <span>span with content</span>.</p>
    </div>
    

    If we want to make the text “content” bold, we can do this easily utilizing both the jQuery click() method and jQuery html() method.

    Below is the Javascript code which will allow the user to be change the content in the span.

    $("#click-me").click(function(){
        $("#div1 span").html("span with <strong>content</strong>");
    });

    The final code and output for this example of how to change text of a span using the jQuery html() method and Javascript is below:

    Code Output:

    Click here to update span.

    We are going to add html to this span with content.

    Full Code:

    <div class="html-code-output">
    <div id="div1">
      <div id="click-me">Click here to update span.</div>
      <p>We are going to add html to this <span>span with content</span>.</p>
    </div>
    </div>
    
    <script>
    
    $("#click-me").click(function(){
        $("#div1 span").html("span with <strong>content</strong>");
    });
    
    </script>
    

    Hopefully this article has been useful for you to understand how to change text in a span using jQuery.

    1. Изменить текст элемента с помощью свойства textContent в JavaScript
    2. Изменение текста элемента с помощью функции createTextNode() в JavaScript

    Текст изменения JavaScript

    В этом руководстве будет обсуждаться, как изменить текст элемента с помощью свойства textContent и функции createTextNode() в JavaScript.

    Изменить текст элемента с помощью свойства textContent в JavaScript

    Если вы хотите заменить старый текст элемента новым текстом, вам нужно получить этот элемент, используя его идентификатор или имя класса, а затем вы можете заменить старый текст новым текстом, используя свойство textContent. Если идентификатор или имя класса не указаны, вы можете использовать атрибут id или class, чтобы присвоить элементу идентификатор или имя класса. Убедитесь, что идентификатор или имя класса уникальны; в противном случае любой элемент с таким же идентификатором также будет изменен. Например, давайте создадим текстовый элемент с помощью тега span и изменим его текст с помощью функции textContent в JavaScript. См. Код ниже.

    <!DOCTYPE html>
    <html>
    <head>
        <title></title>
    </head>
    <body>
        <span id="SpanID"> Old Text </span>
        <script type="text/javascript">
            document.getElementById("SpanID").textContent="New Text";
        </script>
    </body>
    </html>
    

    Выход:

    Код JavaScript помещается в файл HTML в приведенном выше коде, но вы можете разделить их, если хотите. Вы также можете указать условие, при котором текст должен быть изменен, например, нажав кнопку. Если вы не хотите заменять текст, но добавляете новый текст к старому, вы можете использовать метод ниже.

    Изменение текста элемента с помощью функции createTextNode() в JavaScript

    Если вы хотите присоединить новый текст к старому, вам нужно получить этот элемент, используя его идентификатор или имя класса, а затем с помощью функции createTextNode() вы можете создать узел нового текста и использовать appendChild()Вы можете добавить новый текст к старому. Если идентификатор или имя класса не указаны, вы можете использовать атрибут id или class, чтобы присвоить элементу идентификатор или имя класса. Убедитесь, что идентификатор или имя класса уникальны; в противном случае любой элемент с таким же идентификатором также будет изменен. Например, давайте создадим текстовый элемент с помощью тега span и добавим его текст с помощью функции createTextNode() в JavaScript. См. Код ниже.

    <!DOCTYPE html>
    <html>
    <head>
        <title></title>
    </head>
    <body>
        <span id="SpanID"> Old Text </span>
        <script type="text/javascript">
            Myspan = document.getElementById("SpanID");
            Mytxt = document.createTextNode("New text");
            Myspan.appendChild(Mytxt);
        </script>
    </body>
    </html>
    

    Выход:

    Как вы можете видеть в выходных данных, новый текст объединяется со старым текстом.

    Понравилась статья? Поделить с друзьями:
  • Как изменить текст на сайте html
  • Как изменить текст на рабочем столе виндовс 10
  • Как изменить текст на планшете
  • Как изменить текст на отсканированном изображении
  • Как изменить текст на отсканированном документе jpeg