简体   繁体   English

如何使用 JavaScript 更改跨度元素的文本?

[英]How do I change the text of a span element using JavaScript?

If I have a span , say:如果我有一个span ,请说:

<span id="myspan"> hereismytext </span>

How do I use JavaScript to change "hereismytext" to "newtext"?如何使用 JavaScript 将“hereismytext”更改为“newtext”?

For modern browsers you should use:对于现代浏览器,您应该使用:

document.getElementById("myspan").textContent="newtext";

While older browsers may not know textContent , it is not recommended to use innerHTML as it introduces an XSS vulnerability when the new text is user input (see other answers below for a more detailed discussion):虽然较旧的浏览器可能不知道textContent ,但不建议使用innerHTML ,因为当用户输入新文本时它会引入 XSS 漏洞(有关更详细的讨论,请参阅下面的其他答案):

//POSSIBLY INSECURE IF NEWTEXT BECOMES A VARIABLE!!
document.getElementById("myspan").innerHTML="newtext";

Using innerHTML is SO NOT RECOMMENDED .不推荐使用innerHTML Instead, you should create a textNode.相反,您应该创建一个 textNode。 This way, you are "binding" your text and you are not, at least in this case, vulnerable to an XSS attack.这样,您就“绑定”了您的文本,并且至少在这种情况下,您不会容易受到 XSS 攻击。

document.getElementById("myspan").innerHTML = "sometext"; //INSECURE!!

The right way:正确的方式:

span = document.getElementById("myspan");
txt = document.createTextNode("your cool text");
span.appendChild(txt);

For more information about this vulnerability: Cross Site Scripting (XSS) - OWASP有关此漏洞的更多信息:跨站点脚本 (XSS) - OWASP

Edited nov 4th 2017: 2017 年 11 月 4 日编辑:

Modified third line of code according to @mumush suggestion: "use appendChild(); instead".根据@mumush的建议修改了第三行代码:“使用 appendChild(); 代替”。
Btw, according to @Jimbo Jonny I think everything should be treated as user input by applying Security by layers principle.顺便说一句,根据@Jimbo Jonny的说法,我认为应该通过应用分层安全原则将所有内容视为用户输入。 That way you won't encounter any surprises.这样你就不会遇到任何意外。

EDIT: This was written in 2014. A lot has changed.编辑:这是 2014 年写的。很多东西都变了。 You probably don't care about IE8 anymore.您可能不再关心 IE8。 And Firefox now supports innerText . Firefox 现在支持innerText

If you are the one supplying the text and no part of the text is supplied by the user (or some other source that you don't control), then setting innerHTML might be acceptable:如果您是提供文本的人,并且用户(或您无法控制的其他来源)没有提供任何文本部分,那么设置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';

However, as others note, if you are not the source for any part of the text string, using innerHTML can subject you to content injection attacks like XSS if you're not careful to properly sanitize the text first.但是,正如其他人指出的那样,如果您不是文本字符串任何部分的来源,如果您不小心先正确清理文本,则使用innerHTML可能会使您遭受 XSS 等内容注入攻击。

If you are using input from the user, here is one way to do it securely while also maintaining cross-browser compatibility:如果您使用来自用户的输入,这是一种安全的方法,同时还保持跨浏览器的兼容性:

var span = document.getElementById('myspan');
span.innerText = span.textContent = 'newtext';

Firefox doesn't support innerText and IE8 doesn't support textContent so you need to use both if you want to maintain cross-browser compatibility. Firefox 不支持innerText并且 IE8 不支持textContent所以如果你想保持跨浏览器的兼容性,你需要同时使用这两者。

And if you want to avoid reflows (caused by innerText ) where possible:如果您想尽可能避免回流(由innerText引起):

var span = document.getElementById('myspan');
if ('textContent' in span) {
    span.textContent = 'newtext';
} else {
    span.innerText = 'newtext';
}
document.getElementById('myspan').innerHTML = 'newtext';

我使用Jquery ,但以上都没有帮助,我不知道为什么,但这有效:

 $("#span_id").text("new_value");

Here's another way:这是另一种方式:

var myspan = document.getElementById('myspan');

if (myspan.innerText) {
    myspan.innerText = "newtext";
}
else
if (myspan.textContent) {
        myspan.textContent = "newtext";   
}

The innerText property will be detected by Safari, Google Chrome and MSIE. Safari、Google Chrome 和 MSIE 将检测到 innerText 属性。 For Firefox, the standard way of doing things was to use textContent but since version 45 it too has an innerText property, as someone kindly apprised me recently.对于 Firefox,标准的做事方式是使用 textContent 但从 45 版开始,它也有一个 innerText 属性,正如最近有人告诉我的那样。 This solution tests to see if a browser supports either of these properties and if so, assigns the "newtext".此解决方案测试浏览器是否支持这些属性中的任何一个,如果支持,则分配“newtext”。

Live demo: here现场演示:这里

In addition to the pure javascript answers above, You can use jQuery text method as following:除了上面的纯 javascript 答案外,您还可以使用 jQuery文本方法,如下所示:

$('#myspan').text('newtext');

If you need to extend the answer to get/change html content of a span or div elements, you can do this:如果您需要扩展答案以获取/更改 span 或 div 元素的html内容,您可以这样做:

$('#mydiv').html('<strong>new text</strong>');

References:参考:

.text(): http://api.jquery.com/text/ .text(): http://api.jquery.com/text/

.html(): http://api.jquery.com/html/ .html(): http ://api.jquery.com/html/

You may also use the querySelector() method, assuming the 'myspan' id is unique as the method returns the first element with the specified selector:您也可以使用 querySelector() 方法,假设 'myspan' id 是唯一的,因为该方法返回具有指定选择器的第一个元素:

document.querySelector('#myspan').textContent = 'newtext';

developer.mozilla 开发者.mozilla

Like in other answer, innerHTML and innerText are not recommended, it's better use textContent .与其他答案一样,不推荐使用innerHTMLinnerText ,最好使用textContent This attribute is well supported, you can check it this: http://caniuse.com/#search=textContent此属性得到很好的支持,您可以检查它: http ://caniuse.com/#search=textContent

document.getElementById("myspan").textContent="newtext";

这将选择 id myspan的 dom-node 并将其文本内容更改为new text

You can do你可以做

document.querySelector("[Span]").textContent = "content_to_display";

 (function ($) { $(document).ready(function(){ $("#myspan").text("This is span"); }); }(jQuery));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <span id="myspan"> hereismytext </span>

user text() to change span text.用户text()更改跨度文本。

Can't be used with HTML code insertion, something like:不能与 HTML 代码插入一起使用,例如:
var a = "get the file <a href='url'>the link</a>"
var b = "get the file <a href='url'>another link</a>"
var c = "get the file <a href='url'>last link</a>"

using使用
document.getElementById("myspan").textContent=a;
on
<span id="myspan">first text</span>

with a timer but it just shows the reference target as text not runing the code, even tho it does shows correctly on the source code.使用计时器,但它只是将参考目标显示为未运行代码的文本,即使它确实在源代码上正确显示。 If the jquery approch is not really a solution, the use of:如果 jquery 方法不是真正的解决方案,请使用:

document.getElementById("myspan").innerHTML = a to c;
is the best way to make it work.是让它工作的最好方法。

Many people still come across this question (in 2022) and the available answers are not really up to date.许多人仍然遇到这个问题(2022 年),并且可用的答案并不是最新的。

Use innerText is the best method使用innerText是最好的方法

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.正如您在MDM 文档中看到的, innerText是通过 Javascript 检索和更改<span> HTML 元素的文本的最佳方式。

The innerText property is VERY well supported ( 97.53% of all web users according to Caniuse ) innerText属性得到很好的支持(根据 Caniuse的说法, 97.53%的网络用户)

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 ?为什么比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.不要使用innerHTML来更新用户输入的内容,这可能会导致重大漏洞,因为您将设置的字符串内容将被解释并转换为 HTML 标记。

This means users can insert script(s) into your site, this is known as XSS attacks/vulnerabilities (Cross-site scripting).这意味着用户可以将脚本插入您的站点,这称为 XSS 攻击/漏洞(跨站点脚本)。

Why better than textContent ?为什么比textContent更好?

First point textContent isn't supported by IE8 (but I think in 2022 nobody cares anymore). IE8 不支持第一点textContent (但我认为 2022 年不再有人关心)。 But the main element is the true difference of result you can get using textContent instead of innerText .但主要元素是使用textContent而不是innerText可以获得的结果的真正区别。

The example from the MDM documentation is perfect to illustrate that, so we have the following setup: MDM 文档中的示例完美地说明了这一点,因此我们有以下设置:

<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:如果您使用innerText来检索<p id="source">的文本内容,我们会得到:

TAKE A LOOK AT
HOW THIS TEXT
IS INTERPRETED BELOW.

This is perfectly what we wanted.这完全是我们想要的。

Now using textContent we get:现在使用textContent我们得到:


  #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.这就是为什么使用textContent不是正确方法的原因。

Last point最后一点

If you goal is only to append text to a <p> or <span> HTML element, the answer from nicooo.如果您的目标只是将文本附加到<p><span> HTML 元素,那么来自 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);

For this span对于这个跨度

<span id="name">sdfsdf</span>

You can go like this :-你可以这样:-

$("name").firstChild.nodeValue = "Hello" + "World";

I used this one document.querySelector('ElementClass').innerText = 'newtext';我用了这个document.querySelector('ElementClass').innerText = 'newtext';

Appears to work with span, texts within classes/buttons似乎与跨度、类/按钮中的文本一起使用

For some reason, it seems that using "text" attribute is the way to go with most browsers.出于某种原因,似乎使用“文本”属性是大多数浏览器的方式。 It worked for me它对我有用

$("#span_id").text("text value to assign"); $("#span_id").text("要分配的文本值");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM