简体   繁体   English

如何替换 div 元素内段落内的文本?

[英]How do I replace text inside a paragraph inside a div element?

I need to set the text within a Paragraph that is within a DIV element dynamically.我需要动态设置 DIV 元素内的段落内的文本。 I know the divID and can get the div by id using get document.getElementById(divID) This returns the following:我知道 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>

The function should look like this: function 应如下所示:

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注意段落的id总是noteContent1

There are 2 ways you can change the text within HTML tag您可以通过两种方式更改 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 
}

You can use theNode.lastChild to access the p tag as it is the last element within the div tag您可以使用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;
}

Pretty close with your variable name, this assumes that it's html you wanna use.与您的变量名称非常接近,这假设您要使用的是 html。 If it's just a string you can use updateNoteP.innerText instead如果它只是一个字符串,您可以改用 updateNoteP.innerText

If you pass in pID as "noteContent1" this will change the content of the P如果您将 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.

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