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:
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>