0

How can I cloneNode as same as the original one? I want to get the same innerText result with cloned Node, but it didn't work.

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Test</title>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
  </head>
  <body>
    <p>Hello
      World</p>
    <script>
      const p = document.querySelector('p');
      const pCloned = p.cloneNode(true);
      const pText = p.innerText; // Hello World
      const pClonedText = pCloned.innerText; // Hello\n     World
      console.log('pText', pText);
      console.log('pClonedText', pClonedText);
      console.log(pText === pClonedText); // false
  </script>
  </body>
</html>
Owen Young
  • 157
  • 2
  • 8
  • Why is different? You have a newline in your code... Seems correct – pierpy Nov 25 '22 at 11:36
  • Not sure why, but `textContent` appears to be the same for both. – CBroe Nov 25 '22 at 11:38
  • @CBroe I want to use innerText for a normal HTML to text result. but I need to change something on the copied node, so I can't operate the original node, and now the copied node is different from the original one. – Owen Young Nov 25 '22 at 15:18

1 Answers1

0

possible duplicate of this: Javascript cloneNode innerText does not read <br> as \n

better use .textContent instead of .innerText as mentioned in the above question's comments if that fits your purpose. Also check the links mentioned in that post.

Marc Simon
  • 306
  • 1
  • 5