我有以下代码。我试图将所有hello的实例改为hey。我创建了一个变量text来存储这个字符串。然后我试着在该字符串上使用replace方法,但它没有改变该字符串。我希望文本在 <p>
元素标签要改成 嘿嘿嘿嘿但它没有改变。我到底做错了什么?
HTML:
<p id="1">hello hello hello hello</p>
Javascript:
var text = document.getElementById("1").textContent;
text = text.replace(/hello/g,"hey");
你可以像这样做。
为什么不工作
text= elem.textContent
其读取的值。text=replace
因为文本中只有字符串,所以不可能出现。p
elem不是DOM elem var text = document.getElementById("1").textContent;
console.log(text) //direct string
text = text.replace(/hello/g, "hey")
<p id="1">hello hello hello hello</p>
解决办法
var text = document.getElementById("1");
console.log(text) //dom element
text.textContent = text.textContent.replace(/hello/g, "hey")
<p id="1">hello hello hello hello</p>