jQuery append element at first position on the lists

0

jQuery append element at the first position on the lists. We can easily append any element in the first place instead of the last using jQuery. Normally, We will use prepend and before method for append element in the first place. Today, We are going to see both methods with an example.

jQuery append element at first position

1 ) Prepend Method

First of all, We are going to see how we can append the element at the first position using the prepend method like.

var html = "<div class='child-div'>Prepend Element First position</div>";
$("#parent-div").prepend(html);

It’s too easy just pass the HTML string on the prepend method for append it at the first place on the lists. Now, Let’s see HTML example.

<!DOCTYPE html>
<html>
<head>
  <title> jQuery - Prepend Method </title>
</head>
<body>

  <div id="parent-div">
      <div>Hello World</div>
  </div>
  <input type="button" value="add" class="add" />

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
  </script>
  <script>
      $(document).ready(function () {
          $('.add').on('click', function (event) {
              var html = "<div class='child-div'>Prepend Element First position</div>";
        $("#parent-div").prepend(html);
    });
      });
  </script>
  
</body>
</html>

2 ) Before Method

We are going to see the second method for append the element in the first position using the before method like.

var htmloption = "<option>Select All</option>";
$("#parentdropdown option:eq(0)").before(htmloption);

We can easily insert the element in the first place using the before method lets the example.

<!DOCTYPE html>
<html>
  <head>
    <title> jQuery - Before Method </title>
  </head>
  <body>

    <div id="parent-div">
      <select id="parentdropdown">
        <option>First</option>
        <option>Second</option>
        <option>Third</option>
      </select>
    </div>
    <input type="button" value="add" class="add" />

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
    </script>
    <script>
      $(document).ready(function () {
          $('.add').on('click', function (event) {
              var htmloption = "<option>Select All</option>";
              $("#parentdropdown option:eq(0)").before(htmloption);
          });
      });
    </script>

  </body>
</html>

I hope this article useful for you. Please let us know if anything was missing or wrong by comment.

Share.

Leave A Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.