Using javascript to remove the last instance of a specific HTML entity (breadcrumb)

300 Views Asked by At

I need to remove the last instance of

>

from:

<b>
<a href="link">Home</a> &gt;
<a href="link">Category</a> &gt;
<a href="link">Sub-category</a> &gt;
<a href="link">Sub-sub-category</a> &gt;
</b>

I assume regex will need to be employed, but I haven't found any good ways to do it. I'm removing the last instance of the link with

(a:last).remove();

but, after a couple iterations, I get multiple > > > in a row with no links between

4

There are 4 best solutions below

0
On

Could you wrap <a href="link">...</a> &gt; in a span like so: <span><a href="link">...</a> &gt;</span> and then do (span:last).remove();?

It would lead to a cleaner solution with little extra markup.

1
On

How about a solution in CSS instead of javascript?

CSS

.link {
    display: inline-block;
}

.link:after {
    content: ' \003e';
}

.link:last-of-type:after {
    content: '';
}

HTML

<div class="link"> <a href="#">Crumb 1</a> </div>
<div class="link"> <a href="#">Crumb 2</a> </div>
<div class="link"> <a href="#">Crumb 3</a> </div>

see http://jsfiddle.net/stackolee/tzbDe/

0
On

If you can edit the markup, I'd recomment khalid13's answer. Otherwise, you could try showdev's comment to select a text node or hack through it like this:

//where b is your `<b>` element:
var links = b.innerHTML.split('&gt;')
links.pop()
b.innerHTML = links.join('&gt;')

What I'm doing here is splitting the menu into a JS array based on the '>' characters, then removing the last element of the array and joining it all back together again.

0
On

If you really want to do this in plain javascript, you can do this:

// pass the node before where you want to look for the ">"
function removeTrailingGt(start) {
    var node = start.nextSibling;
    while (node && node.nodeType === 3) {
        if (node.nodeValue.indexOf(">") !== -1) {
            node.nodeValue = node.nodeValue.replace(">", "");
            break;
        }
        node = node.nextSibling;
    }
}

It starts from the last link in your containing object and then searches all following text nodes and removes the first ">" that it finds.

Working demo: http://jsfiddle.net/jfriend00/BC647/