Skip to content
Fetching contributors…
Cannot retrieve contributors at this time
53 lines (52 sloc) 2.78 KB
<?xml version="1.0"?>
<entry type="method" name="prependTo" return="jQuery">
<title>.prependTo()</title>
<signature>
<added>1.0</added>
<argument name="target" type="Selector, Element, jQuery">
<desc>A selector, element, HTML string, or jQuery object; the matched set of elements will be inserted at the beginning of the element(s) specified by this parameter.</desc>
</argument>
</signature>
<desc>Insert every element in the set of matched elements to the beginning of the target.</desc>
<longdesc>
<p>The <code><a href="/prepend">.prepend()</a></code> and <code>.prependTo()</code> methods perform the same task. The major difference is in the syntax-specifically, in the placement of the content and target. With<code> .prepend()</code>, the selector expression preceding the method is the container into which the content is inserted. With <code>.prependTo()</code>, on the other hand, the content precedes the method, either as a selector expression or as markup created on the fly, and it is inserted into the target container.</p>
<p>Consider the following HTML:</p>
<pre><code>&lt;h2&gt;Greetings&lt;/h2&gt;
&lt;div class="container"&gt;
&lt;div class="inner"&gt;Hello&lt;/div&gt;
&lt;div class="inner"&gt;Goodbye&lt;/div&gt;
&lt;/div&gt;</code></pre>
<p>We can create content and insert it into several elements at once:</p>
<pre><code>$('&lt;p&gt;Test&lt;/p&gt;').prependTo('.inner');</code></pre>
<p>Each inner <code>&lt;div&gt;</code> element gets this new content:</p>
<pre><code>&lt;h2&gt;Greetings&lt;/h2&gt;
&lt;div class="container"&gt;
&lt;div class="inner"&gt;
&lt;p&gt;Test&lt;/p&gt;
Hello
&lt;/div&gt;
&lt;div class="inner"&gt;
&lt;p&gt;Test&lt;/p&gt;
Goodbye
&lt;/div&gt;
&lt;/div&gt;</code></pre>
<p>We can also select an element on the page and insert it into another:</p>
<pre><code>$('h2').prependTo($('.container'));</code></pre>
<p>If an element selected this way is inserted elsewhere, it will be moved into the target (not cloned):</p>
<pre><code>&lt;div class="container"&gt;
&lt;h2&gt;Greetings&lt;/h2&gt;
&lt;div class="inner"&gt;Hello&lt;/div&gt;
&lt;div class="inner"&gt;Goodbye&lt;/div&gt;
&lt;/div&gt;</code></pre>
<p>If there is more than one target element, however, cloned copies of the inserted element will be created for each target after the first.</p>
</longdesc>
<example>
<desc>Prepends all spans to the element with the ID "foo"</desc>
<css><![CDATA[div { background:yellow; }]]></css>
<code><![CDATA[$("span").prependTo("#foo"); // check prepend() examples]]></code>
<html><![CDATA[<div id="foo">FOO!</div>
<span>I have something to say... </span>]]></html>
</example>
<category slug="manipulation/dom-insertion-inside"/>
<category slug="version/1.0"/>
</entry>
Something went wrong with that request. Please try again.