Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

insert before pre tag

I need to insert from javascript some text into a pre tag. I tried the following:

<!DOCTYPE html>
<html>

<body>
  
  <pre id='test'> some
text</pre>

  <script>
    // Create a "span" element:
    const newNode = document.createElement("span");
    // Create a text node:
    const textNode = document.createTextNode(" Water ");
    // Append text node to "span" element:
    newNode.appendChild(textNode);

    // Insert before existing child:
    const list = document.getElementById("test");
    list.insertBefore(newNode, list.children[0]);
  </script>

</body>

</html>

but my output is:

 some
text water

but I need:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 water some
text

>Solution :

You would need to insert before the firstChild, not the first element.

const newNode = document.createElement("span");
const textNode = document.createTextNode(" Water ");
newNode.appendChild(textNode);
const list = document.getElementById("test");
list.insertBefore(newNode, list.firstChild);
<pre id='test'> some
text</pre>

You can simplify this by using Element#prepend.

const span = Object.assign(document.createElement('span'), {textContent: " Water "});
document.getElementById("test").prepend(span);
<pre id='test'> some
text</pre>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading