William
William

Reputation: 1069

Remove all span elements by classname?

I have a classname called notag. When i click a button, it triggers my onclick event to call my function. Within the function i want it to remove / delete all span elements that has that classname notag.

My attempts are below but no luck! Please help thanks.

onclick="replaceQueuePlaylist()"

function replaceQueuePlaylist()
{
    $("span").attr('notag').remove(); //dont work
    $('.notag').remove(); //also dont work
}

Upvotes: 0

Views: 10763

Answers (4)

Adnan Bin Mustafa
Adnan Bin Mustafa

Reputation: 1215

Just add these lines in your function. Happy coding

$("span.notag").each(function () {
    $(this).remove();
});

Upvotes: 0

mrid
mrid

Reputation: 5796

$("span").attr('notag').remove(); //dont work

This won't work because your elements have a class named notag, and not an attribute. class itself is an attribute with value notag in <div class='notag'> hello world </div>

There's no need to explicitly use .each() as using $(selector).remove() will automatically iterate through each element with the selection criteria and remove it.

$('#delete-em').on('click', function(){
    $('.delete-me').remove();  
});
.delete-me{
    height: 50px;
    width: 50px;
    margin: 5px;
    background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class='delete-me'></div>
<div class='delete-me'></div>
<div class='delete-me'></div>
<div class='delete-me'></div>

<button id="delete-em">Remove</button>

Upvotes: 6

Yosvel Quintero
Yosvel Quintero

Reputation: 19070

With jQuery.remove() you can directly remove all the set of matched elements from the DOM:

function replaceQueuePlaylist() {
    $('span.notag').remove();
}

Upvotes: 2

Qsprec
Qsprec

Reputation: 275

Try this one;

 function replaceQueuePlaylist() {
    $("span.notag").each(function () {
        $(this).remove();
    });
 }

Finds all the spans with notag class name and delete them.

Upvotes: 1

Related Questions