[英]How do I replace text inside a paragraph inside a div element?
我需要動態設置 DIV 元素內的段落內的文本。 我知道 divID 並且可以使用 get document.getElementById(divID) 通過 id 獲取 div 這將返回以下內容:
<div id="mynote72031" class="mydiv" ondrop="drop(event,this.id)" ondragover="allowDrop(event)" style="cursor: move; display: block; top: 19px; left: 19px; width: 375px;">
<a style="top:0px; right:5px; position:absolute; color:#F00" href="javascript:;" onclick="hideElement(this)">X</a>
<p id="noteContent1" ondblclick="editContent(this)">Note Number: 1</p>
</div>
function 應如下所示:
function updateNote(divID, paragraphInnerHTML) {
var updateNoteP = document.getElementById(divID);
//Update Paragraph inside the DIV here
}
注意段落的id總是noteContent1
您可以通過兩種方式更改 HTML 標簽中的文本
function updateNote(divID, paragraphInnerHTML) {
var updateNoteP = document.getElementById(divID);
//Update Paragraph inside the DIV here
let $targetEle = updateNoteP.childNodes[1]
// use innerHTML
$targetEle.innerHTML = paragraphInnerHTML
// or textContext
$targetEle.textContent = paragraphInnerHTML
}
您可以使用Node.lastChild訪問p
標簽,因為它是div
標簽中的最后一個元素
function updateNote(divID, paragraphInnerHTML) {
var updateNoteP = document.getElementById(divID);
//Update Paragraph inside the DIV here
let pElement = updateNoteP.lastChild;
pElement.innerHTML = paragraphInnerHTML;
}
與您的變量名稱非常接近,這假設您要使用的是 html。 如果它只是一個字符串,您可以改用 updateNoteP.innerText
如果您將 pID 作為“noteContent1”傳遞,這將更改 P 的內容
function updateNote(pID, paragraphInnerHTML) {
var updateNoteP = document.getElementById(divID);
// check that element is found
if (updateNoteP) {
// update inner html
updateNoteP.parentElement.children[1].innerHTML = paragraphInnerHTML
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.