首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >是否获取innerHtml、innerText或nodeValue并排除嵌套子对象?

是否获取innerHtml、innerText或nodeValue并排除嵌套子对象?
EN

Stack Overflow用户
提问于 2019-05-08 14:18:03
回答 1查看 240关注 0票数 1

我试图将我的DOM保存为某种JSON格式,树中的一个键是content。这段代码运行得“很好”,但只适用于简单的情况。我使用now nodeValue只从第一个子元素中获取文本,它给了我很好的结果,但是当结构包含像br这样的元素时,它就崩溃了。

代码语言:javascript
复制
const uploadDom = (node, path, siblingsLeft, order) => {
  for (let item of node) {
    order = order + 1;
    database.ref("dom/" + path + "/" + order).update({
      id: item.id,
      type: item.tagName,
      class: item.className,
      content: item.childNodes[0].nodeValue
    });
    if (item.children.length) {
      siblingsLeft = item.children.length - 1;
      path = path + order + `/`;
      uploadDom(item.children, path, siblingsLeft, order);
    }
    if (siblingsLeft > 1) {
      a = order + "/";
      path = path.replace(a, "");
      siblingsLeft = 1;
    }
  }
};

以下是HTML结构示例:(请注意,此结构始终是动态的)

代码语言:javascript
复制
<div id="wrapper">
<!-- wrapper has no text content so I want content value of null -->
   <p>I want to save this text as content value of P tag</p>
   <div class="wrapper-2">
   <!-- wrapper has no text content so I want content value of null -->
      <p>This P contains <br> new line element</p>
      <!-- I'm using nodeValue of first child so content will be = 'This P contains' -->
      <!-- content should be = 'This P contains <br> new line element' -->
      <p>I want to save this text as content value of P tag</p>
   </div>
</div>

我正在努力找出更聪明的方法来保存我的DOM树,尽管我正在为上面的例子中保存文本内容的方法而苦苦挣扎。

EN

回答 1

Stack Overflow用户

发布于 2019-05-08 14:26:16

您可以将DOM树保存到有效的json中,如下所示

代码语言:javascript
复制
let json = JSON.stringify(wrapper.innerHTML)

console.log(JSON.parse(json));
代码语言:javascript
复制
<div id="wrapper">
<!-- wrapper has no text content so I want content value of null -->
   <p>I want to save this text as content value of P tag</p>
   <div class="wrapper-2">
   <!-- wrapper has no text content so I want content value of null -->
      <p>This P contains <br> new line element</p>
      <!-- I'm using nodeValue of first child so content will be = 'This P contains' -->
      <!-- content should be = 'This P contains <br> new line element' -->
      <p>I want to save this text as content value of P tag</p>
   </div>
</div>

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56034613

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档