Suliman Sharif Suliman Sharif - 3 months ago 8
jQuery Question

Removing Child Elements in Javascript

I know this has been extensively answered but alas I have had no luck with previous code.

So I want to remove all the span elements in this div element when the user onclicks a button.

THE HTML

<div id="sequence-label" class="scrollingDiv" style="visibility: hidden;">
<li>H :</li>
<span class="spanUnselected">T</span>
<span class="spanUnselected">F</span>
<span class="spanUnselected">G</span>
<span class="spanUnselected">Q</span>
<span class="spanUnselected">G</span>
</div>


**THE JS **

$('#sequence-remove-pdb').click(sequenceRemovePdb);

function sequenceRemovePdb() {
document.getElementById("sequence-label").style.visibility = "hidden";
workspaceSideChain();
var mySeq = document.getElementById("sequence-label");

}


Things I have tried

Tried to remove all the elements as children of sequence-label

mySeq.empty();


Tried to remove by class selected

mySeq.remove(".spanUnselected");


Tried to remove by firstChild Elements

while (mySeq.firstChild) {
mySeq.removeChild(mySeq.firstChild);
}


Tried to remove by childNodes also over how many elements are in sequence-label and still nothing.

Any ideas?

Answer

The Problem
You're mixing jQuery and vanilla javascript in a way that does not work.

Specifically, you're getting an element in vanilla javascript here:

var mySeq = document.getElementById("sequence-label");

Then you are trying to remove elements using jQuery:

mySeq.empty();

and

mySeq.remove(".spanUnselected"); 

The Solution
The solution is simple enough. Get the element as a jQuery object first, then your functions will work:

var mySeq = jQuery("#sequence-label");
// Then act on it with jQuery as you see fit.
mySeq.find('.spanUnselected').remove();

Also, be sure your event bindings take place inside of a document ready:

jQuery(function($) {
    $('#sequence-remove-pdb').click(function() {sequenceRemovePdb;});
});
Comments