Suliman Sharif Suliman Sharif - 1 year ago 90
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.


<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>

**THE JS **


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


Things I have tried

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


Tried to remove by class selected


Tried to remove by firstChild Elements

while (mySeq.firstChild) {

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

Any ideas?

Answer Source

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:




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.

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

jQuery(function($) {
    $('#sequence-remove-pdb').click(function() {sequenceRemovePdb;});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download