Search code examples
javascriptjqueryprototypejs

Remove the last link in a div, but keep the "link" text - how?


I am building some breadcrumbs for a nav. This is done before the page is rendered via a templating language. Once the page is rendered, I need to do some figuring.

Instead of doing a bunch of IF/ELSE on the templating side, is there a way to render a div with links.. lets say..

<div id="bc_links">
<a>Link one</a> >
<a>Link 22</a> >
<a>Link 33</a> >
<a>Link 44</a> >
</div>

THEN do some jquery or prototype (have access to both libraries) and be able to identify that link44 is the last link, and make the display this:

<div id="bc_links">
<a>Link one</a> >
<a>Link 22</a> >
<a>Link 33</a> >
 Link 44
</div>

Any help would be appreciated.


Solution

  • You can use .innerWrap() to wrap the text in a <span> tag, then select the new <span> tag and .unwrap() it, removing the anchor tag from the DOM and keeping the text intact.

    $('#bc_links').children().last().wrapInner('<span />').children().unwrap();
    

    Here is a demo: http://jsfiddle.net/7dB8R/

    Update

    You can also use .contents() to remove text-nodes (the caret at the end of the line):

    $('#bc_links').contents().last().remove();
    

    Here is a demo: http://jsfiddle.net/7dB8R/1/