简体   繁体   English

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

[英]Get innerHtml or innerText or nodeValue and exclude nested child?

I'm trying to save my DOM into some JSON format and one key in the tree is content . 我正在尝试将DOM保存为某种JSON格式,并且树中的一个键是content This code works 'fine', but only for simple cases. 此代码“正常”运行,但仅适用于简单情况。 I'm using now nodeValue to grab the text only from the first child, and it gives me good results, but it's breaking when the structure contains elements like br . 我现在使用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;
    }
  }
};

Here is example HTML structure: (please note this structure is always dynamic) 这是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>

I'm trying to figure out smarter way to save my DOM tree, although I'm struggling with the way I can save text content as in the example above. 我正在尝试寻找一种更聪明的方法来保存DOM树,尽管我在上面的示例中仍在努力地保存文本内容。

You can save your DOM tree into valid json as follows 您可以将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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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