Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - Removing all anchor tags with a specific class from a div

Tags:

jquery

In certain cases, and for reasons that go beyond the scope of this question, the anchors are getting repeated. Here's a sample div:

<div class="unifyRepeat listing">
    <a class="businessAnchor" name="abcchildcareandlearningcenter"></a>
    <a class="businessAnchor" name="abcchildcareandlearningcenter"></a>
    <a class="businessAnchor" name="abcchildcareandlearningcenter"></a>
    <a class="businessAnchor mceItemAnchor" name="abcchildcareandlearningcenter"></a>
    <table class="tblListing">
        <tbody>
            <tr>
                <td>
                    <p class="bold">ABC Child Care and Learning Center</p>
                    <p>Jane Smith</p>
                    <p>(555) 555-1234</p>
                </td>
                <td>
                    <img alt="" src="images/ABCchildcare.jpg">
                </td>
                <td>
                </td>
            </tr>
        </tbody>
    </table>
    <a class="linkToTop" href="#top">^ Top</a>
</div>

Here's the jQuery that appends the anchor and attempts to remove any existing ones:

$('#businessListings div.listing').each(function() {
    var name = $(this).find('p:first').text(),
        cleanedName = name.replace(/\W/g, '').toLowerCase();

    $('ul#businessListingLinks').append('<li><a href="#' + cleanedName + '">' + name + '</a>');

    var anchor = '<a class="businessAnchor" name="' + cleanedName + '"></a>';
    $(this).remove('a.businessAnchor');
    //$(this).each('a.businessAnchor').remove();
    $(this).prepend(anchor);
});

I thought that the remove() line would select all anchor tags with the class "businessAnchor", but it's not.

As you can see, I tried the each() function, but that didn't work. I'm not sure if that's because I didn't implement it properly, or some other reason.

like image 584
marky Avatar asked Mar 25 '23 05:03

marky


1 Answers

Try this:

$(this).find('a.businessAnchor').remove();

Since, from the markup, it seems that a.businessAnchor are direct child of div, so you can do this too:

$(this).children('a.businessAnchor').remove();
like image 71
palaѕн Avatar answered Apr 10 '23 10:04

palaѕн