1

<article>
<div><p></p></div>

<div><p></p></div>
<div><p></p></div>
<div><p></p></div>
<div><p></p></div>
<div><p></p></div>
<img/>
<p> i want to add element after this</p>


</article>

I have an article element in which many elements are its child i want to add a last element before closing tag of article element.

i want some code in jquery to do this randomly at runtime.

my intention is to add before article element the lastelemnt is just sample as here it can be div, ul, etc

3 Answers3

5

via JQuery

$("article").last().after( "<p>Test</p>" )
martinii
  • 141
  • 10
5

Pure Javascript

You can use a pure javascript solution like below. This code:

  1. Gets the <article> by using document.getElementById()
  2. Uses .appendChild() to add the newly created element to the end of the last child (which is the end of the article).

var article = document.getElementById("article");
var element = document.createElement("h1");
var text = document.createTextNode("Test");
element.appendChild(text);

article.appendChild(element);
#article {
  background-color: red;
}
<article id="article">
  <div>
    <p></p>
  </div>

  <div>
    <p></p>
  </div>
  <div>
    <p></p>
  </div>
  <div>
    <p></p>
  </div>
  <div>
    <p></p>
  </div>
  <div>
    <p></p>
  </div>
  <img/>
  <p> i want to add element after this</p>


</article>

jQuery

This solution uses jQuery. This code uses .append() to add the element into the end of the article. Personally, I believe that jQuery is cleaner, but sometimes not the best solution.

var article = document.getElementById("article");
var element = document.createElement("h1");
var text = document.createTextNode("Test");
element.appendChild(text);

$("#article").append(element);
#article {
  background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<article id="article">
  <div>
    <p></p>
  </div>

  <div>
    <p></p>
  </div>
  <div>
    <p></p>
  </div>
  <div>
    <p></p>
  </div>
  <div>
    <p></p>
  </div>
  <div>
    <p></p>
  </div>
  <img/>
  <p> i want to add element after this</p>


</article>
Aniket G
  • 3,471
  • 1
  • 13
  • 39
2

You can use .append(): $("article").append( "<p>Test</p>" );

.append(): Insert content, specified by the parameter, to the end of each element in the set of matched elements.

$(document).ready(function(){
  $("article").append( "<p>Test</p>" );
});
article{
  background-color:red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<article>
<div><p></p></div>

<div><p></p></div>
<div><p></p></div>
<div><p></p></div>
<div><p></p></div>
<div><p></p></div>
<img/>
<p> i want to add element after this</p>


</article>
Mukyuu
  • 6,436
  • 8
  • 40
  • 59