- Как изменить текст элемента span с помощью JavaScript?
- How to Use JavaScript to Change Text in Span
- Changing the Text in a Span with JavaScript using the Id and TextContent property
- Other Articles You’ll Also Like:
- About The Programming Expert
- How to change the text of a span element using JavaScript?
- Example: Using textContent Property
- Output
- Using innerText Property
- Example: Using innerText property
- Output
- Conclusion
Как изменить текст элемента span с помощью JavaScript?
Хотя старые браузеры могут не знать textContent , не рекомендуется использовать innerHTML , поскольку это создает уязвимость XSS, когда новый текст вводится пользователем (см. Другие ответы ниже для более подробного обсуждения):
//POSSIBLY INSECURE IF NEWTEXT BECOMES A VARIABLE!! document.getElementById("myspan").innerHTML="newtext";
как вставить атрибут стиля в span , используя здесь javascript? — person bouncingHippo; 10.09.2012
@bouncingHippo document.getElementById (myspan) .setAttribute (стиль, cssvalues); — person Gregoire; 11.09.2012
@Gregoire имейте в виду, что ваше решение не работает по крайней мере на ie8. См. stackoverflow.com/questions/2119300/ — person MeTTeO; 13.03.2013
должен быть способ объединить эти два ответа в один. это точно такой же ответ. — person john-jones; 18.02.2014
Это не устанавливает текст, а устанавливает HTML, который принципиально отличается. — person Brad; 11.10.2014
@gregoire — Как уже отмечали другие, ваш ответ уязвим для XSS. Этот вопрос уже был просмотрен около 80 тысяч раз, что означает, что многие люди, вероятно, приняли это решение и, возможно, внесли ненужные утечки xss. Не могли бы вы подумать об обновлении своего ответа, чтобы вместо этого использовать textContent , чтобы новым людям было предложено использовать правильные и безопасные методы? — person Tiddo; 21.01.2015
@Tiddo textContent не поддерживается в IE8 и более ранних версиях, и я надеюсь, что вы никогда не будете использовать в своем скрипте непосредственно незарегистрированный пользовательский ввод. — person Gregoire; 21.01.2015
Совет. Не помешает взглянуть на следующую запись в блоге: Плохой, неправильно понятый innerText Отличная статья, чтобы получить представление о различиях между .innerText и .textContent , производительности, а также о том, что происходит« за кулисами ». Здесь есть важная информация, ИМО. 🙂 — person Dennis98; 01.10.2016
спасибо, это помогло мне . для получения длинной строки со значением символа Эмберсона — person Prasanth_Rubyist; 05.12.2017
Использование innerHTML НЕ РЕКОМЕНДУЕТСЯ. Вместо этого вы должны создать textNode. Таким образом, вы «привязываете» свой текст и, по крайней мере, в этом случае, не уязвимы для XSS-атаки.
document.getElementById("myspan").innerHTML = "sometext"; //INSECURE!!
span = document.getElementById("myspan"); txt = document.createTextNode("your cool text"); span.appendChild(txt);
Дополнительные сведения об этой уязвимости: Межсайтовый скриптинг (XSS) — OWASP Отредактировано 4 ноября 2017 г .: Изменена третья строка кода в соответствии с предложением @mumush: «вместо этого используйте appendChild ();».
Между прочим, согласно @Jimbo Jonny, я думаю, что все должно рассматриваться как пользовательский ввод, применяя безопасность по слоям принцип. Так вы не встретите никаких сюрпризов.
Хотя вы абсолютно правы, innerHTML требуя осторожности, обратите внимание, что ваше решение использует innerText , который не поддерживается в Firefox. quirksmode.org/dom/html Он также использует textContent , который не поддерживается в IE8. Вы можете структурировать код, чтобы обойти эти проблемы. — person Trott; 02.10.2014
В вопросе ничего не говорится о вводе данных пользователем, поэтому общее заявление о том, что innerHTML не рекомендуется, является нелепым. Не говоря уже о том, что после дезинфекции он все еще в порядке. Идея о том, что нужно дезинфицировать вводимые пользователем данные, ТАК НЕ СВЯЗАНА с этим конкретным вопросом. В лучшем случае следует сделать небольшую заметку в конце, в которой говорится: кстати: если это пользовательский ввод, сначала убедитесь, что вы проделали дезинфекцию или используйте метод X, который в этом не нуждается. — person Jimbo Jonny; 23.01.2016
Кроме того, создание элементов НАМНОГО быстрее, чем использование innerHTML. — person Samuel Rondeau-Millaire; 24.03.2016
Использование appendChild на самом деле не изменяет текст, а только добавляет к нему. Используя ваш код здесь, диапазон из исходного вопроса в конечном итоге приведет к прочтению вашего классного текста hereismytexty. Может быть, span.innerHTML = «»; тогда appendChild? — person ShaneSauce; 09.05.2018
@JimboJonny Когда речь идет о таких вопросах, как этот, которые были просмотрены более 650 000 раз, то, что конкретно задает OP, совершенно не имеет значения. Поэтому я считаю разумным упоминать уязвимость XSS на видном месте в интересах общественной безопасности. — person yeah22; 16.03.2021
РЕДАКТИРОВАТЬ: Это было написано в 2014 году. Вы, вероятно, больше не заботитесь об IE8 и можете забыть об использовании innerText . Просто используйте textContent и покончим с этим, ура. Если вы предоставляете текст, и никакая часть текста не предоставляется пользователем (или каким-либо другим источником, который вы не контролируете), тогда установка innerHTML может быть приемлемой:
// * Fine for hardcoded text strings like this one or strings you otherwise // control. // * Not OK for user-supplied input or strings you don't control unless // you know what you are doing and have sanitized the string first. document.getElementById('myspan').innerHTML = 'newtext';
Однако, как отмечают другие, если вы не являетесь источником какой-либо части текстовой строки, использование innerHTML может подвергнуть вас атакам с внедрением контента, таким как XSS, если вы сначала не будете осторожны и не очистите текст должным образом. Если вы используете ввод от пользователя, вот один из способов сделать это безопасно, сохраняя при этом кроссбраузерность:
var span = document.getElementById('myspan'); span.innerText = span.textContent = 'newtext';
Firefox не поддерживает innerText , а IE8 не поддерживает textContent , поэтому вам нужно использовать оба, если вы хотите поддерживать кроссбраузерность. И если вы хотите избежать перекомпоновки (вызванной innerText ), где это возможно:
var span = document.getElementById('myspan'); if ('textContent' in span) < span.textContent = 'newtext'; >else
How to Use JavaScript to Change Text in Span
There are a couple of ways that we can change the text in a span using JavaScript. The first way we can do this is with the innerHTML property:
document.getElementById("div1").innerHTML = "Changing this text in #div1";
Let’s say we have the following HTML:
The innerHTML property gives us the ability to insert HTML into our div and change the HTML that was in there. By doing this we can change the span text that was in there too.
So to change the span text in the div above from “November” to “December” we can use the following code:
var currDiv = document.getElementById("div1"); currDiv.innerHTML = "Today is December 3rd.";
Changing the Text in a Span with JavaScript using the Id and TextContent property
Another way we can change the text of a span using JavaScript is to give the span an id, and target the id with the getElementById method.
Let’s say we have the following HTML:
We can give the span an id of “span1”.
We can then target the “span1” id and change the text of it using the textContent property. Here is the code:
Hopefully this article has been useful for you to understand how to change text in a span using Javascript.
Other Articles You’ll Also Like:
- 1. Using JavaScript to Get the Width of an Element
- 2. Remove Commas From Array in JavaScript
- 3. Using JavaScript to Get the Last Day of the Month
- 4. Get the First Child Element and Change it with JavaScript
- 5. Remove Undefined Values From an Array in JavaScript
- 6. How to Check if a String Contains Vowels in JavaScript
- 7. Uncheck a Radio Button Using JavaScript
- 8. Convert an Array of Values into a String Without Commas in JavaScript
- 9. Using JavaScript to Get Substring Between Two Characters
- 10. Convert an Array to Set in JavaScript
About The Programming Expert
The Programming Expert is a compilation of a programmer’s findings in the world of software development, website creation, and automation of processes.
Programming allows us to create amazing applications which make our work more efficient, repeatable and accurate.
At the end of the day, we want to be able to just push a button and let the code do it’s magic.
You can read more about us on our about page.
How to change the text of a span element using JavaScript?
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 and 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.
Hello World
Output
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.
Hello World
Output
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.