Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

DOM2JSON #36

Open
Sunny-117 opened this issue Nov 3, 2022 · 3 comments
Open

DOM2JSON #36

Sunny-117 opened this issue Nov 3, 2022 · 3 comments

Comments

@Sunny-117
Copy link
Owner

{
  tag: 'DIV',
  children: [
    {
      tag: 'SPAN',
      children: [
        { tag: 'A', children: [] }
      ]
    },
    {
      tag: 'SPAN',
      children: [
        { tag: 'A', children: [] },
        { tag: 'A', children: [] }
      ]
    }
  ]
}

function dom2Json(domtree) {
  let obj = {};
  obj.name = domtree.tagName;
  obj.children = [];
  domtree.childNodes.forEach((child) => obj.children.push(dom2Json(child)));
  return obj;
}
@mengqiuleo
Copy link

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <div class="box">
    <p class="p">hello world</p>
    <div class="person">
      <span class="name">DOM2JSON</span>
      <span class="age">100</span>
    </div>
  </div>

  <script>
    function DOM2JSON(domTree){
      if(!domTree) return;
      let rootObj = {
        tagName: domTree.tagName,
        children: []
      }

      const children = domTree.children
      if(children){
        Array.from(children).forEach((element, i) => {
          rootObj.children[i] = DOM2JSON(element)
        })
      }
      return rootObj
    }

    console.log(DOM2JSON(document.querySelector('.box')))
  </script>
</body>
</html>

@kangkang123269
Copy link

function DOMtoJSON(node) {
  const obj = {
    tag: node.tagName.toLowerCase(),
    children: [],
  };
  for (let i = 0; i < node.children.length; i++) {
    obj.children.push(DOMtoJSON(node.children[i]));
  }
  return obj;
}

@bearki99
Copy link

function dom2json(domtree) {
  let obj = {};
  obj.tag = domtree.tagName.toLowerCase();
  obj.children = [];
  domtree.children.forEach((item) => {
    obj.children.push(dom2json(item));
  });
  return obj;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants