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
4
Answers
so it seems you need to use innerText and template literals:
How about something like this?
https://jsfiddle.net/ptqby9rL/
Yes, to be inside the pre you can do:
You would need to insert before the
firstChild
, not the first element.You can simplify this by using
Element#prepend
.Use
insertAdjacentHTML
with positionafterbegin
which inserts the specified HTML content at the beginning of thepre
element: