skip to Main Content

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


  1. Chosen as BEST ANSWER

    so it seems you need to use innerText and template literals:

    start = document.getElementById("putItHere").innerText
    document.getElementById("putItHere").innerText = `water ` + start
     
    <pre id="putItHere">some
    text
    </pre>


  2. How about something like this?

    const list = document.getElementById("test");
    list.parentNode.insertBefore(newNode, list);
    

    https://jsfiddle.net/ptqby9rL/

    Yes, to be inside the pre you can do:

    const list = document.getElementById("test");
    list.innerHTML = "<span> Water </span>" + list.innerHTML; 
    
    Login or Signup to reply.
  3. 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>
    Login or Signup to reply.
  4. Use insertAdjacentHTML with position afterbegin which inserts the specified HTML content at the beginning of the pre element:

    // 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 at the beginning of the pre element:
    const preElement = document.getElementById("test");
    preElement.insertAdjacentHTML('afterbegin', newNode.outerHTML);
    <pre id='test'> some
    text</pre>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search