Как изменить значение 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);

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

    Учитывая HTML-документ, и задача состоит в том, чтобы изменить текст элемента span. Для изменения содержимого используются два свойства.

    • Свойство HTML DOM textContent: это свойство устанавливает / возвращает текстовое содержимое определенного узла и всех его потомков. При установке свойства textContent дочерние узлы удаляются и заменяются одним текстовым узлом, имеющим указанную строку.

      Синтаксис:

      • Вернуть текстовое содержимое узла:
        node.textContent
        
      • Установите текстовое содержимое узла:
        node.textContent = текст
        

      Значения свойств: он содержит текст с одним значением, который определяет текстовое содержимое указанного узла.

      Возвращаемое значение: возвращает строку, представляющую текст узла и всех его потомков. Он возвращает null, если элемент является документом, типом документа или обозначением.

    • Свойство HTML DOM innerText: это свойство устанавливает / возвращает текстовое содержимое определенного узла и всех его потомков. При установке свойства innerText все дочерние узлы удаляются и заменяются одним текстовым узлом, имеющим указанную строку.

      Синтаксис:

      • Вернуть текстовое содержимое узла:
        node.innerText
        
      • Установите текстовое содержимое узла:
        node.innerText = текст
        

      Значения свойств: он содержит текст с одним значением, который определяет текстовое содержимое указанного узла.

      Возвращаемое значение: возвращает строку, представляющую «визуализированное» текстовое содержимое узла и всех его потомков.

    Пример 1. В этом примере содержимое изменяется с помощью свойства textContent .

    <!DOCTYPE HTML>

    < html >

    < head >

    < title >

    JavaScript | Change the text of a span element

    </ title >

    </ 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 onclick = "gfg_Run()" >

    Change

    </ button >

    < p id = "GFG_DOWN" style =

    "color:green; font-size: 20px; font-weight: bold;" >

    </ 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 >

    </ body >

    </ html >

    Выход:

    Пример 2: В этом примере содержимое изменяется с помощью свойства innerText .

    <!DOCTYPE HTML>

    < html >

    < head >

    < title >

    JavaScript | Change the text of a span element

    </ title >

    </ 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 onclick = "gfg_Run()" >

    Change

    </ button >

    < p id = "GFG_DOWN" style =

    "color:green; font-size: 20px; font-weight: bold;" >

    </ 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 >

    </ body >

    </ html >

    Выход:

    29.12.2019JavaScript, Веб-технологии, Веб-технологии Вопросы

    Учитывая HTML-документ и задача состоит в том, чтобы изменить текст элемента span. Есть два свойства, используемые для изменения содержимого.

    • HTML DOM textContent Property: это свойство устанавливает / возвращает текстовое содержимое определенного узла и всех его потомков. Устанавливая свойство textContent, дочерние узлы удаляются и заменяются одним текстовым узлом с указанной строкой.

      Синтаксис:

      • Вернуть текстовое содержимое узла:
        node.textContent
        
      • Установите текстовое содержимое узла:
        node.textContent = text
        

      Значения свойства: содержит текст с одним значением, который определяет текстовое содержимое указанного узла.

      Возвращаемое значение: возвращает строку, представляющую текст узла и всех его потомков. Он возвращает ноль, если элемент является документом, типом документа или нотацией.

    • HTML DOM innerText Свойство: Это свойство устанавливает / возвращает текстовое содержимое определенного узла и всех его потомков. При установке свойства innerText все дочерние узлы удаляются и заменяются одним текстовым узлом с указанной строкой.

      Синтаксис:

      • Вернуть текстовое содержимое узла:
        node.innerText
        
      • Установите текстовое содержимое узла:
        node.innerText = text
        

      Значения свойства: содержит текст с одним значением, который определяет текстовое содержимое указанного узла.

      Возвращаемое значение: возвращает строку, представляющую «визуализированное» текстовое содержимое узла и всех его потомков.

    Пример 1. Этот пример изменяет содержимое с помощью свойства textContent .

    <!DOCTYPE HTML> 

    <html

        <head

            <title

                JavaScript | Change the text of a span element

            </title>

        </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 onclick = "gfg_Run()"

                Change

            </button>

            <p id = "GFG_DOWN" style

                "color:green; font-size: 20px; font-weight: bold;">

            </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

        </body

    </html>                    

    Выход:

    Пример 2. Этот пример изменяет содержимое с помощью свойства innerText .

    <!DOCTYPE HTML> 

    <html

        <head

            <title

                JavaScript | Change the text of a span element

            </title>

        </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 onclick = "gfg_Run()"

                Change

            </button>

            <p id = "GFG_DOWN" style

                "color:green; font-size: 20px; font-weight: bold;">

            </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

        </body

    </html>                    

    Выход:

    Рекомендуемые посты:

    • JQuery | Изменить текст элемента span
    • JavaScript | Получить текст элемента span
    • JQuery | Получить текст элемента span
    • Как изменить текст метки с помощью JavaScript?
    • Изменить элемент класса JavaScript
    • Как изменить цвет текста в зависимости от цвета фона с помощью JavaScript?
    • Как изменить атрибут src элемента img в JavaScript / jQuery?
    • Как динамически изменить атрибут стиля элемента с помощью JavaScript?
    • Как выделить весь текст в текстовом вводе HTML при нажатии с использованием JavaScript?
    • Как изменить текст кнопки с помощью jQuery?
    • Как изменить текст заполнителя с помощью jQuery?
    • Как показать элемент span для каждой строки, нажатой в AngularJS?
    • Как изменить идентификатор элемента с помощью jQuery?
    • Как изменить имя элемента HTML с помощью jQuery?
    • Как изменить содержимое <textarea> с помощью JavaScript?

    JavaScript | Изменить текст элемента span

    0.00 (0%) 0 votes

    Понравилась статья? Поделить с друзьями:

    Читайте также:

  • Как изменить значение input через js
  • Как изменить значение input jquery
  • Как изменить значение input javascript
  • Как изменить значение final переменной java
  • Как изменить значение f на фотоаппарате

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии