Home > OS >  Is there a way to get the label attached to an element to javascript?
Is there a way to get the label attached to an element to javascript?

Time:10-19

I'm trying to delete a label attached to a check box, as well as the checkbox itself. I can easily delete the checkbox using

<script>
    var Check = document.createElement("input")
                Check.setAttribute("name", Name);
                Check.setAttribute("id", Name)
                

                var Label = document.createElement("label")
                var labelText = document.createTextNode(Name);

                Label.setAttribute("for", Name)

                Label.appendChild(labelText);

                var LineBreak = document.createElement("br");

                Check.setAttribute("type", "checkbox")



                document.getElementById("MyList").appendChild(Check);
                document.getElementById("MyList").appendChild(Label);
                    document.getElementById("MyList").appendChild(LineBreak);

                    Check.addEventListener('change', event =>{
                        
                        document.getElementById("MyList").removeChild(event.target)
                        
            }
        </script>                

but I can't get the label. Any ideas?

CodePudding user response:

You already have the handle to the label in a variable Label. The variable is visible in the closure. Therefore you can simply delete it via Label.remove() inside event listener function.

Check.addEventListener('change', event =>{
  document.getElementById("MyList").removeChild(event.target)
  Label.remove();                      
}

See how to remove element from the DOM

CodePudding user response:

You need to select the DOM element correctly. The Event.target is referencing your input. You can traverse the DOM with an existing element or select it globally as such.

document.querySelector('label').remove()

Edit: after you added more code and appear to already have the DOM element in a variable, you can simply do Label.remove()

CodePudding user response:

Your attempt is way to difficult! Simply use the remove() function:

// id for element to remove
let id = 'MyList';

// removed the input with that id
document.querySelector(`#${id}`).remove();

// removes the label connected to an input with the id
document.querySelector(`[for="${id}"]`).remove();
<label for="MyList">Test</label><input type="checkbox" id="MyList">

  • Related