-1

This is my html:

    <div id="border1">parents nodes text
        <div id="border2">the target node
            <div id="border3">the main nodes child node</div>
        </div>
    </div>


I want to save first div output which is parents nodes text . when i use
let big = document.getElementById("border1").innerText

it will give me all texts in all of divs!

How can i solve this problem?

  • You are trying to get the first text node, does this answer your question? [How to get the text node of an element?](https://stackoverflow.com/questions/6520192/how-to-get-the-text-node-of-an-element) – Hamza Abdaoui Dec 29 '20 at 14:29

1 Answers1

1

do this:

const mainElId = "border1";
const mainEl = document.getElementById(mainElId);
let data = {};
mainEl.querySelectorAll('*').forEach(n => {
  data[n.getAttribute('id')] = n.innerText;
  n.remove();
}
);
data[mainElId] = mainEl.innerText;
console.log(data);
<div id="border1">parents nodes text
        <div id="border2">the target node
            <div id="border3">the main nodes child node</div>
        </div>
    </div>
MotemaddeN
  • 524
  • 3
  • 9