Ying Rui Wong Ying Rui Wong - 3 months ago 23
HTML Question

jQuery/JavaScript: how to remove all elements in the first <li> except <a>text</a>

I have a nested list.


<ul id="menu-main-menu" class="nav sn-nav">
<li id="menu-item-38" class="menu-item menu-item-type-yawp_wim menu-item-object-yawp_wim menu-item-38">
<div class="yawp_wim_wrap">
<div class="widget-area">
<div id="custommetawidget-3" class="yawp_wim_widget customMetaWidget">
<span class="yawp_wim_title"></span>
<ul>
<li><a href="1">Site Admin</a></li>
<li><a href="2">Log out</a></li>
</ul>
</div>
</div>
</div>
</li>
<li>
<a href="3">test</a>
</li>
</ul>


I want to remove all elements of first
<li id='menu-item-38'>
but leave
<a>
.

Just like the second
<li>
.


I found a similar link: http://jsfiddle.net/yJrb7/1/


But it keep not working.

var li = document.getElementsByClassName('menu-item')[0];
var links = document.getElementsByTagName('a');
for(var i=0;i<li.childNodes.length;i++){
if(li.childNodes[i].nodeName!=links)
li.removeChild(li.childNodes[i--]);
}


EDIT:

Hey guys, sorry my fault, I didn't make clear.

What I need actually is

<ul id="menu-main-menu" class="nav sn-nav">
<li><a href="1">Site Admin</a></li>
<li><a href="2">Log out</a></li>
<li><a href="3">test</a></li>
</ul>

Answer
window.onload = function() {
    //declare an instance of DocumentFragment Type;
    var fragment = document.createDocumentFragment();
    var liList = document.getElementById("menu-item-38").querySelectorAll("li");
    for (var i = 0; i < liList.length; i++) {
        //copy these li into the fragment
        fragment.appendChild(liList[i]);
    }
    var removeObj = document.getElementById("menu-item-38");
    var parentElement = removeObj.parentNode;
    //remove li whose id id [menu-item-38]
    parentElement.removeChild(removeObj);
    //add fragment to the parmentElement
    parentElement.appendChild(fragment);
}
Comments