tags:

views:

19

answers:

3

If i have:

<div id="test"></div>

How do I select the test div and then add <div id="pre-test"> before the test div so it looks like this:

<div id="pre-test"><div id="test"></div>

Thanks guys

+2  A: 

$("<div id='pre-test'/>").insertBefore("#test");

insertBefore documentation.

Alternatively, you can use the .before(...) method like so:

$("#test").before("<div id='pre-test'/>");

Strelok
A: 

You can use insertBefore (http://api.jquery.com/insertBefore/)

$('<div id="pre-test">').insertBefore($('#test'));
Niels Bom
@strelokstrelok beat me to it :)Our solutions look different but work similar (afaik).Do check out the jQuery documentation, it's pretty good. And you can use Google to search in it. site:http://api.jquery.com insert
Niels Bom
A: 

Two ways. You can Either do:

$('#test').before($('#test'));

That would do it, but you can't chain it. A better approach is to use .insertBefore()

$('<div/>', {
   id:  'pre-test'
}).insertBefore($('#test'));

That way, you don't need to re-query the newly created element if you want to apply more methods on it. For instance:

$('<div/>', {
   id:  'pre-test'
}).insertBefore($('#test')).css('background-color', 'red').fadeOut('slow', function(){
    $(this).fadeIn('slow');
});

Ref.: .insert(), .insertBefore()

jAndy