How can I remove a child node in HTML using JavaScript?

前端 未结 9 1429
野的像风
野的像风 2020-12-12 20:22

Is there a function like document.getElementById(\"FirstDiv\").clear()?

9条回答
  •  攒了一身酷
    2020-12-12 20:57

    A jQuery solution

    HTML

    
    

    Javascript

    // remove child "option" element with a "value" attribute equal to "2"
    $("#foo > option[value='2']").remove();
    
    // remove all child "option" elements
    $("#foo > option").remove();
    

    References:

    Attribute Equals Selector [name=value]

    Selects elements that have the specified attribute with a value exactly equal to a certain value.

    Child Selector (“parent > child”)

    Selects all direct child elements specified by "child" of elements specified by "parent"

    .remove()

    Similar to .empty(), the .remove() method takes elements out of the DOM. We use .remove() when we want to remove the element itself, as well as everything inside it. In addition to the elements themselves, all bound events and jQuery data associated with the elements are removed.

提交回复
热议问题