Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using .closest() to insert before - not working

I have the following markup in a list (of repeated identical list format):

    <li class="item">
        <div class="outer">
            <p>Some text</p>
            <div class="inner">Some div text</div>
        </div>
        <a class="link" href="#">Link</a>
    </li>

and I wish to move the a.link to between the p and the div.inner in each list item.

I am using the following script:

    $("li.item a.link").each(function() {
        $(this).closest("div.inner").before(this);
    }); 

but I am just getting the error: "$(this).closest is not a function"

Why is .closest() not working... it seems to be recommended often. Is there a different way of achieving this?

Many thanks.

like image 945
AndyiBM Avatar asked Nov 14 '11 13:11

AndyiBM


1 Answers

Try -

$("li.item a.link").each(function() {
    $(this).closest('li').find(".inner").before(this);
});

This would also work if closest isn't working for you -

$("li.item a.link").each(function() {
    $(this).parent('li').find(".inner").before(this);
});  

Demo - http://jsfiddle.net/MkD8j/2/

Both of these work by finding the closest parent 'li' element and then searching that for the 'inner' div element. You original code was searching for the 'div.inner' element using the closest function which finds parent elements, the 'div.inner' element is a sibling of the link so it was not finding anything.

like image 146
ipr101 Avatar answered Oct 13 '22 23:10

ipr101