获取innerHtml或innerText或nodeValue并排除嵌套子级?

时间:2019-05-08 06:18:03

标签: javascript firebase

我正在尝试将DOM保存为JSON格式,树中的一个键是content。此代码“正常”运行,但仅适用于简单情况。我现在正在使用nodeValue仅从第一个孩子那里抓取文本,它给了我很好的结果,但是当结构包含诸如br之类的元素时,它就坏了。

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结构:(请注意,该结构始终是动态的)

<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树,尽管我在上面的示例中仍在努力地保存文本内容。

1 个答案:

答案 0 :(得分:0)

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

let json = JSON.stringify(wrapper.innerHTML)

console.log(JSON.parse(json));
<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>