PRANAV
PRANAV

Reputation: 1111

Insert html befor </body> tag jquery

I want to insert a paragraph element <p> at the end of <body>, just before the </body>.

I've tried insertBefore() as follow, but it doesn't work as expected.

$( "<p>Test</p>" ).insertBefore( "</body>" );

Upvotes: 5

Views: 12449

Answers (3)

Tushar
Tushar

Reputation: 87203

This means that you want to append content to the <body>. append() will add the content to the end of the selector element.

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

$(document.body).append("<p>Test</p>");
p {
  color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>

<body>
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
</body>

Upvotes: 14

Orhan K&#246;roglu
Orhan K&#246;roglu

Reputation: 41

Just use:

.append();

From the jQuery API for .append( ):

"Description: Insert content, specified by the parameter, to the end of each element in the set of matched elements." (http://api.jquery.com/append/)

So

$('body').append("<p>Test</p>");

will insert the html to the end of body which is before the closing tag < /body>.

Upvotes: 4

Rycochet
Rycochet

Reputation: 2938

You can use either

$("body").append("<p>Test</p>")

or

$("<p>Test</p>").appendTo("body")

They both do the same thing, but the second is more useful if also wanting to save the created element:

var $test = $("<p>Test</p>").appendTo("body");
// Do something else here
$test.css("background", "red");

See here for more information.

Upvotes: 2

Related Questions