5

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.

Leniel Maccaferri
  • 100,159
  • 46
  • 371
  • 480
AndyiBM
  • 379
  • 5
  • 17

1 Answers1

6

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.

ipr101
  • 24,096
  • 8
  • 59
  • 61
  • Solution 2 worked perfectly - thanks ipr101 - and for the explanation too. Really not sure why closest not working though - I'm sure I've got it working on another site, so I'll debug that when I can. – AndyiBM Nov 14 '11 at 14:42