简体   繁体   English

改变里面的文字 <h2> 文字我会改变 </h2> 使用javascript的元素

[英]Change text inside <h2> Text I would change </h2> element using javascript

I need to change the text inside 我需要更改里面的文字

HTML element using javascript, but I have no idea about how to do it. 使用javascript的HTML元素,但我不知道如何做到这一点。 ¿Any help? ¿有什么帮助吗?

I've got it defined like: 我把它定义为:

 <h2 id="something">Text I want to change.</h2> 

Im trying to do it with: 我试图这样做:

 document.getElementById("something").value = "new text"; 

But it doesn't work. 但它不起作用。

Thanks 谢谢

你可以使用innerHTML

document.getElementById("something").innerHTML = "new text";

If the element only contains text, textContent works better and faster than innerHTML 如果元素只包含文本,则textContentinnerHTML更好,更快

document.getElementById("something").textContent = 'new text';

Good luck :) 祝好运 :)

Though the following code would be the fastest alternative to slow .innerHTML : 虽然以下代码是减慢.innerHTML最快替代方案:

var element = document.getElementById('something');

// removing everything inside the node
while (element.firstChild) {
    element.removeChild(element.firstChild);
}

// appending new text node
element.appendChild(document.createTextNode('new text'));

And here is the benchmark: 以下是基准:

JSPerf

JSPerf: http://jsperf.com/replace-text-in-node JSPerf: http ://jsperf.com/replace-text-in-node

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

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