jQuery: The Write Less, Do More JavaScript Library

Manipulation/before

From jQuery JavaScript Library

Jump to: navigation, search

« Back to Manipulation

before( content )

Insert content before each of the matched elements.
Arguments:
contentString, Element, jQuery
Content to insert before each target.

Examples:
Inserts some HTML before all paragraphs.

$("p").before("<b>Hello</b>");

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
                    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="../jquery-latest.js"></script>
  
  <script>
  $(document).ready(function(){
    $("p").before("<b>Hello</b>");
  });
  </script>
  <style>p { background:yellow; }</style>
</head>
<body>
  <p> is what I said...</p>
</body>
</html>

Inserts a DOM element before all paragraphs.

$("p").before( document.createTextNode("Hello") );

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
                    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="../jquery-latest.js"></script>
  
  <script>
  $(document).ready(function(){
    $("p").before( document.createTextNode("Hello") );
  });
  </script>
  <style>p { background:yellow; }</style>
</head>
<body>
  <p> is what I said...</p>
</body>
</html>

Inserts a jQuery object (similar to an Array of DOM Elements) before all paragraphs.

$("p").before( $("b") );

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
                    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="../jquery-latest.js"></script>
  
  <script>
  $(document).ready(function(){
    $("p").before( $("b") );
  });
  </script>
  <style>p { background:yellow; }</style>
</head>
<body>
  <p> is what I said...</p><b>Hello</b>
</body>
</html>

NameType