簡體   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