Languages
[Edit]
EN

JavaScript - prepend element

3 points
Created by:
Welsh
902

In this article, we would like to show you how to prepend element using JavaScript.

Quick solution:

var parent = document.querySelector('#parent');

parent.prepend(document.createElement('div'));

Warning: prepend() method appeared around 2015 in major web browsers.

 

Practical examples

In the below, you can find two solutions that solves the problem.

1. Custom solution

In this section, you can find solution that works in older web brosers too.

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<body>
  <div id="container">
    <div>Element 1</div>
    <div>Element 2</div>
    <div>Element 3</div>
  </div>
  <script>

    function prependChild(parent, child) {
    	var placeholder = parent.firstChild;
        if (placeholder) {
            parent.insertBefore(child, placeholder);
        } else {
            parent.appendChild(child);
        }
    }
    
    var container = document.querySelector('#container');

    var element = document.createElement('div');
    element.textContent = 'New element';

    prependChild(container, element);

  </script>
</body>
</html>

 

2. prepend() methods

In this example, we use prepend() method that appeared around 2015 in major web browsers.

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<body>
  <div id="container">
    <div>Element 1</div>
    <div>Element 2</div>
    <div>Element 3</div>
  </div>
  <script>

    var container = document.querySelector('#container');

    var element = document.createElement('div');
    element.textContent = 'New element';

    container.prepend(element);

  </script>
</body>
</html>

 

References

  1. Element.prepend() - Web APIs | MDN
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join