.before() methodThe .before() method in jQuery is used to insert content before each matched element (outside).
.before() method Syntax.before(content,[content]) .before(function)
| Parameter | Type | Description |
|---|---|---|
content |
htmlString,element,text | DOM content to insert after each matched elements. |
function(index,oldHtml) |
Function | A function returning an HTML string,DOM element(s),text or jQuery Object. The index parameter is the position of the element in the set.oldHtml is the old HTML value |
.before(content,[content])Insert HTML content before all paragraphs
HTML
<div class="container">
<p>Learn JavaScript</p>
<p>Learn jQuery</p>
</div>
jQuery
$("p").before("<p> Lautturi.com </p>");
Result
<div class="container">
<p> Lautturi.com </p>
<p>Learn JavaScript</p>
<p> Lautturi.com </p>
<p>Learn jQuery</p>
</div>
Move the dom element (not clone)
HTML
<div id="container">
<h2>tutorial</h2>
<p>Learn JavaScript</p>
<p>Learn jQuery</p>
<p>Learn Python</p>
</div>
jQuery
$("#container").before($('h2'));
Result
<h2>tutorial</h2>
<div id="container">
<p>Learn JavaScript</p>
<p>Learn jQuery</p>
<p>Learn Python</p>
</div>
.before(function)Add links for all items
HTML
<ul>
<li>JavaScript</li>
<li>jQuery</li>
<li>Python</li>
</ul>
jQuery
$("li").before(function(index,oldHtml){
return '<li><a href="lautturi.com/' + oldHtml + '">' + oldHtml + '</a></li>';
});
Result
<ul>
<li><a href="lautturi.com/JavaScript">JavaScript</a></li>
<li>JavaScript</li>
<li><a href="lautturi.com/jQuery">jQuery</a></li>
<li>jQuery</li>
<li><a href="lautturi.com/Python">Python</a></li>
<li>Python</li>
</ul>
