简体   繁体   中英

remove dropdown node on page load

I have this dropdown and I would like to remove all of it's children when the page loads. Here is my code.

 <select id="mylist"> <option value="B">B</option> <option value="D">D</option> <option value="E">E</option> <option value="F">F</option> <option value="R">R</option> </select>` 

I use the detach()

 $(window).on('load',function(){ $('#mylist>option').detach(); }); 

Jquery method to keep the values for the case that you want to re-append the list without loosingany events or data.

You can use empty() to remove all the child, so if you want to do it when the page is loaded you have to do:

$( document ).ready(function() {
   $("#mylist").empty();
});

With this option you will remove the child and all kind of data stored inside those nodes. Documentation: jQuery empty documentation

If you want to keep data you can use .detach() , jQuery detach documentation

Why is everyone suggesting the use of jQuery? He's clearly a beginner.
I would use the document API for this, you don't need a whole library for one function.

 document.addEventListener("DOMContentLoaded", function () { for(var i = 0; i<document.getElementsByTagName("select"); i++){ var b = document.getElementsByTagName("select")[i]; b.parentElement.removeChild(b); } }); 

Set select html to blank.

 $('#mylist').html(''); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select id="mylist"> <option value="B">B</option> <option value="D">D</option> <option value="E">E</option> <option value="F">F</option> <option value="R">R</option> </select> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM