views:

60

answers:

4

Hi,

I have html code like this:

<li>
<a href=''>Example</a>&nbsp;<a href='' class='sub'>Edit</a>&nbsp;<a href='' class='sub'>Delete</a>
</li>

and I want to remove everything after the first </a>, including the spaces. What is the most elegant and simple way to do this? I have achieved my purpose with the following jquery:

$('li').children(".sub").remove();    
$('li').html($('li').html().replace(/&nbsp;/g,''));

but the second line looks too much like a hack. Is there a better way?

+2  A: 

You could do something like this instead:

$('li a:first-child').each(function() {
    $(this).parent().html(this);
});​

This would clean out the parent including event handlers on those elements then put the first <a> back. It would also maintain any event handlers on the anchor you're keeping, you can give it a try here. Passing a DOM element to .html() is a shortcut for .empty() and .append(), just making it a bit more terse.

Nick Craver
Thanks for the link to jsfiddle, looks like a very useful site!
Amati
+1  A: 

What about this?

$('li').html($('li').find("a:first").html())

EDIT 1: The above code is wrong. Try the following:

$('li').find("a:first").appendTo($('li').html(""));

Thanks Nick.

Zafer
This would append the HTML *inside* the anchor, not keeping the anchor :)
Nick Craver
Are you sure? I've tested it and it works... $('li').find("a:first").html() gets the html of the anchor. The answer should be the code that gives <li><a..>Example</a></li>.
Zafer
@Zafer - Yup, try it here: http://jsfiddle.net/nick_craver/Vp47G/2/ notice "Example" is no longer a link :)
Nick Craver
Thanks, you're right... I put it in one line again :). But this time it works.
Zafer
+1  A: 

The easiest way would be to perhaps wrap the Edit/Delete links you're wanting to remove inside of a div (or other element of your choice) and then remove it all at once. You're almost there with the first line of code.

Instead of putting a class='sub' on each anchor, you could instead do something like:

<li>
<a href=''>Example</a><div class='sub'>&nbsp;<a href=''>Edit</a>&nbsp;<a href=''>Delete</a></div>
</li>

And then you'd have:

$('li').children(".sub").remove(); 

Just as you currently do, and it should remove the div, with the spaces.

Delebrin
That's a good suggestion and I may end up having to do it like that but for now I'd prefer to use as little extra html, as possible. With Mic's suggestion, I can even get rid of the ".sub" class.
Amati
+4  A: 

You can try:

$('li').html($('li a:first-child'));
Mic