I need to set the text within a Paragraph that is within a DIV element dynamically. I know the divID and can get the div by id using get document.getElementById(divID) This returns the following:
<div id="mynote72031" 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>
The function should look like this:
function updateNote(divID, paragraphInnerHTML) {
var updateNoteP = document.getElementById(divID);
//Update Paragraph inside the DIV here
}
Note that the id of the paragraph is always noteContent1
CodePudding user response:
There are 2 ways you can change the text within HTML tag
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
}
CodePudding user response:
You can use the Node.lastChild to access the p
tag as it is the last element within the div
tag
function updateNote(divID, paragraphInnerHTML) {
var updateNoteP = document.getElementById(divID);
//Update Paragraph inside the DIV here
let pElement = updateNoteP.lastChild;
pElement.innerHTML = paragraphInnerHTML;
}
CodePudding user response:
Pretty close with your variable name, this assumes that it's html you wanna use. If it's just a string you can use updateNoteP.innerText instead
If you pass in pID as "noteContent1" this will change the content of the 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
}
}