before() Method - Javascript jQuery Method and Property

Javascript examples for jQuery Method and Property:before

Description

The before() method inserts specified content before the selected elements.

Syntax

Parameter Require Description
content Require HTML elements/jQuery objects/DOM elements content to insert
function(index) Optional.function that returns the content to insert
  • index - Returns the index position of the element in the set

The following code shows how to Insert content before each <p> element:

Demo Code

ResultView the demo in separate window

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $("p").before("<p>Hello world!</p>");
    });/*from   w  ww  .  j ava  2s.  com*/
});
</script>
</head>
<body>

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

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

</body>
</html>

Related Tutorials