4

I have the following javascript working to insert AJAX responses into a div with id results:

document.getElementById("results").innerHTML=xmlhttp.responseText;

However, this adds all new elements after those already present. I need for the new elements to be inserted before everything else.

I know this is probably very trivial but I can't seem to find anyway to do it myself.

Thanks for any help!

lampwins
  • 920
  • 1
  • 9
  • 25
  • 4
    No, it doesn't. It replaces them. – Quentin Jan 26 '12 at 13:48
  • possible duplicate of [how insert element before anchor using javascript](http://stackoverflow.com/questions/6415819/how-insert-element-before-anchor-using-javascript) – Gordon Jan 26 '12 at 13:49
  • right now, every AJAX response is added to the div. – lampwins Jan 26 '12 at 13:50
  • And a possible duplicate of http://stackoverflow.com/questions/814564/inserting-html-elements-with-javascript – Tim Jan 26 '12 at 13:50
  • 1
    please point out why none of http://stackoverflow.com/search?q=insert+before+javascript helped answer your question – Gordon Jan 26 '12 at 13:51

4 Answers4

16

With modern js you can utilize the prepend method. Currently caniuse.com says only of IE, Edge, and OperaMini are not supported.

ParentNode.prepend(nodesToPrepend);

e.g.,

ParentNode.prepend(newDiv);

Also, it automatically converts text into a text node so you could do the following for your use case:

document.getElementById("results").prepend(xmlhttp.responseText);
Ulad Kasach
  • 11,558
  • 11
  • 61
  • 87
4

You want either this

results.insertAdjacentHTML( 'beforebegin', xmlhttp.responseText );

or this

results.insertAdjacentHTML( 'afterbegin', xmlhttp.responseText );

(the variable results of course being a reference to the DOM element)

So, the first one will insert the new content before the element itself (as a previous sibling), and the second one will insert it inside the element before any other children).

Šime Vidas
  • 182,163
  • 62
  • 281
  • 385
3

I don't remember the exact syntax, but it something like:

var newDiv = document.createElement("div");
newDiv.innerHTML=xmlhttp.responseText;
document.getElementById("results").childNodes.addAt(0,newDiv);

if you can use jQuery, it's just simple as:

$("#results").prepend(xmlhttp.responseText);
Alex Dn
  • 5,465
  • 7
  • 41
  • 79
0

I was exploring the issue on clear JS so here is an example how do I fix the issue with simple node manipulation. It can be correct approach same as not. There is two options both working.

const userInput = document.getElementById('input-number');
const history = document.getElementById('history');
const addBtn = document.getElementById('btn-add');

function getUserInput(){
  return parseInt(userInput.value);
}

function add(){
  let userInsert = getUserInput();
  let elementToAdd = document.createElement("p");
  elementToAdd.textContent = userInsert;
  /* option one */
  //if (history.hasChildNodes()){
  //  history.insertBefore(elementToAdd, history.firstChild);
  //} else {
  //  history.appendChild(elementToAdd);
  //}
  /* option two */
  history.insertAdjacentHTML("afterbegin", `<p>${elementToAdd.textContent}</p>`);
}

addBtn.addEventListener('click', add);
#history {
  margin: 1rem;
  width: 40rem;
  max-width: 90%;
  border: 1px solid #023d6d;
  border-radius: 10px;
  padding: 1rem;
  color: #023d6d;
}
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha2/dist/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha2/dist/js/bootstrap.bundle.min.js"></script>
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Basics</title>
    <link
      href="https://fonts.googleapis.com/css?family=Roboto:400,700&display=swap"
      rel="stylesheet"
    />
  </head>
  <body class="container">
    <header>
      <h1>Add History</h1>
    </header>
    <div class="row">
      <div class="col-sm-11">
        <input class="form-control" type="number" id="input-number" placeholder="Enter content here"/>
      </div>
      <div class="col-sm-1">
        <button type="button" class="btn btn-primary" id="btn-add">+</button>
      </div>
    </div>
    <div class="row">
      <div class="col-md-12">
        <div class="content-container">
          <section id="history"></section>
          </div>
      </div>
    </div>
  </body>
</html>