如何从Javascript中的另一个孩子中删除孩子?
问题描述:
我试图访问li
元素中的div
,然后将其删除。但我需要通过另一个父母div
访问它,其中包含li
。我在这方面的尝试没有奏效。这是我曾尝试过的:parentDiv.childNodes[0].removeChild(document.getElementsById('removeThisChild')
。如何从Javascript中的另一个孩子中删除孩子?
有谁知道我该如何做到这一点?
谢谢:)
更新
下面是HTML代码:
<head>
\t <script type="text/javascript">
\t \t window.onload = function() {
\t \t \t var ul = document.getElementById('ul')
\t \t \t ul.childNodes[0].removeChild(document.getElementById('div'))
\t \t }
\t </script>
</head>
<body>
<ul id="ul">
\t <li id="li">this is the LI text <div id='div'>this is the div text</div></li>
</ul>
</body>
</html>
答
我已经做了代码笔 - http://codepen.io/dmoojunk/pen/dMVgzb
var child = document.querySelector('#li');
child.parentElement.querySelector('li > div').remove();
你能不能显示你的html标签,比如html页面。有很多选择。 – 7urkm3n
你可以给'div',你想删除一个'id'吗? – John
我不知道你的代码是否可以工作 - 但为了纠正一个错字 - 当你使用getElementById选择元素时,你不会在Element中包含“s”:... parentDiv.childNodes [0] .removeChild(document .getElementById('removeThisChild').... – gavgrif