[英].textContent not replacing text
I'm new to use javascript but having been running into an issue regarding the .textContent function in a script editing an existing webpage. 我是使用JavaScript的新手,但是在编辑现有网页的脚本中遇到了有关.textContent函数的问题。
Instead of replacing the text content, it simply appends the string to the end. 而不是替换文本内容,它只是将字符串附加到末尾。 Looking at the HTML, the original text is in a span while the text I intended as a replacement ends up outside the span but still in the div. 查看HTML,原始文本在跨度中,而我打算替换的文本最终在跨度之外但仍在div中。 How would I go about replacing the span text entirely? 我将如何完全替换跨度文本?
It ends up looking like this 最终看起来像这样
<div class="errorMessage" data-reactid="180"><span>Original Text</span>Intended Replacement text.</div>
Give your <span>
an id like <span id="error-id">
, then use document.getElementById('error-id')
to get a reference to the span. 给您的<span>
一个ID,例如<span id="error-id">
,然后使用document.getElementById('error-id')
获取对该范围的引用。 Or you could just move the class you already have to the span instead of the div, and continue to use document.getElementsByClassName("errorMessage")
. 或者,您可以只将已有的类移至span而不是div,然后继续使用document.getElementsByClassName("errorMessage")
。
Update: Randy Casburn's suggestion is good too. 更新:兰迪·卡斯本的建议也很好。
var ele = document.querySelector('.errorMessage span').textContent = 'Intended Replacement text'; /* InnerHTML can also be used but it is slower than the textContent as it parses HTML */ // ele.innerHTML = 'Intended Replacement text';
<div class="errorMessage" data-reactid="180"><span>Original Text</span></div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.