irishwill200 irishwill200 - 28 days ago 6
Javascript Question

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
}

Answer

$("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>