jQuery insertBefore()

Introduction

Insert a <span> element before each <p> element:

View in separate window

<!DOCTYPE html>
<html>
<head>
<script 
 src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
</script>/*  ww w.j ava2  s .c  om*/
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("<span>Hello world!</span>").insertBefore("p");
  });
});
</script>
</head>
<body>

<button>Insert span element before each p element</button>

<br><br>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>

</body>
</html>

The insertBefore() method inserts HTML elements before the selected elements.

$(content).insertBefore(selector)
Parameter
Optional
Description
content

Required.

the content to insert.
If content is an existing element, it will be moved from its current position.
selector
Required.
where to insert the content



PreviousNext

Related