繁体   English   中英

使用Javascript将HTML中的段落替换为新段落

[英]Replace paragraph in HTML with new paragraph using Javascript

我试图用用Javascript创建的段落替换HTML文档中的p 页面加载后,将用t替换two

var two = document.getElementById("two");

document.onload = function myFunction() {
  var p = document.createElement("p");
  var t = document.createTextNode("I am the superior text");
  p.appendChild(t);
  document.getElementById("p");
  document.two = p;
};

您可以只替换#two元素的文本内容:

 var two = document.getElementById("two"); window.onload = function () { var t = "I am the superior text"; two.textContent = t; }; 
 <p id="two">Lorem ipsum dolor sit amet.</p> 

如果使用createTextNode ,则需要使用two.textContent = t.textContent来获取textNode对象的实际内容。

请注意,您不能通过直接分配来替换DOM中的现有节点。 那就是你想做的。

您不能将节点直接替换为文档,而可以尝试使用innerHTML:

document.onload = function () {
  document.getElementById("two").innerHTML = "I am the superior text";
};

暂无
暂无

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

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