Languages
[Edit]
EN

JavaScript - custom prependChild method

3 points
Created by:
Geospatial-Palus
660

In this article, we would like to show you how to create a custom prependChild() method in JavaScript.

Note:

In JavaScript, there's a prepend method, but in this example, we show a custom implementation of a method that appends a child at the beginning of a container element.

Quick solution:

function prependChild(parent, child) {
    var placeholder = parent.firstChild;
    if (placeholder) {
        parent.insertBefore(child, placeholder);
    else {
        parent.appendChild(child);
    }
}

 

Practical example

In this example, we create prependChild() function that appends child element at the beginning of a parent element. To do so, the method is checking firstChild property and uses insertBefore() and appendChild() methods.

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

 

See also

  1. JavaScript - prepend element

References

  1. Node.firstChild - Web APIs | MDN
  2. Node.insertBefore() - Web APIs | MDN
  3. Node.appendChild() - 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