[英]complex dom traversal using javascript
Code for 01.js: 01.js的代码:
var childp = document.getElementById('selected-plays').getElementsByTagName('li');
function getElementsRequired(childp) {
var listitem = [];
var i = 0;
for(i = 0 ; i <childp.length; i++){
// console.log(childp[i].childNodes.length);
//condition to filter leaf nodes which are 'li'.
if ((childp[i].childNodes.length - 1))
listitem.push(childp[i]);
}
//Loop for removing li's which are not direct sibling of ul with class="selected-plays"
for(i =0 ; i<listitem.length; i++){
if(listitem[i].childNodes[1].getElementsByTagName('a').length){
console.log(listitem[i].childNodes[1].getElementsByTagName('a'));
listitem.splice(i,1);
}
}
return listitem;
}
in console: 在控制台中:
getElementsRequired(childp);
code for body of 01.html: 01.html正文的代码:
<body>
<h2>Selected Shakephere plays</h2>
<ul id="selected-plays">
<li>Comedies
<ul>
<li><a href="/asyoulikeit/">As You Like It</a></li>
<li>All's Well That Ends Well</li>
<li>A Midsummer Night's Dream</li>
<li>Twelfth Night</li>
</ul>
</li>
<li>Tragedies
<ul>
<li><a href="hamlet.pdf">Hamlet</a></li>
<li>Macbeth</li>
<li>Romeo and Juliet</li>
</ul>
</li>
<li>Histories
<ul>
<li>Henry IV (<a href="mailto:henryiv@king.co.uk">email</a>)
<ul>
<li>Part I</li>
<li>Part II</li>
</ul>
</li>
<li><a href="http://www.shakespeare.co.uk/henryv.htm">Henry V</a></li>
<li>Richard II</li>
</ul>
</li>
</ul>
</body>
Elements to be selected are first 'li'siblings of class="selected-plays"
. 要选择的元素是
'li'siblings of class="selected-plays"
第一个'li'siblings of class="selected-plays"
。 The problem is now that traversal of dom gives more element blocks , but it should give only 3 blocks namely "Comedies"
, "Tragedies"
, "Histories"
. 现在的问题是,遍历dom会给出更多的元素块,但是应该只给出3个块,即
"Comedies"
, "Tragedies"
, "Histories"
。 How do I remove the extra element block which is number 4 and contains Henry IV? 如何删除编号为4且包含亨利四世的额外元素块?
jsbin for this is here: http://jsbin.com/vital/2/edit jsbin在这里: http ://jsbin.com/vital/2/edit
You can use jQuery's $.clone()
and $.remove()
to make this easier. 您可以使用jQuery的
$.clone()
和$.remove()
来$.clone()
此操作。 Clone will give you a new element so that you don't destroy the HTML in your DOM. 克隆将为您提供一个新元素,这样您就不会破坏DOM中的HTML。 Remove will then remove the child UL from the newly cloned LI.
然后,删除操作将从新克隆的LI中删除子UL。
http://jsbin.com/jeloloto/2/edit http://jsbin.com/jeloloto/2/edit
$('button').on('click', function() {
var $categoryLIs = $("#selected-plays").children("li");
var categories = getCategories($categoryLIs);
debugger;
})
var getCategories = function($elements) {
var categories = new Array();
$elements.each(function(index) {
var element = $elements[index];
var newElement = $.clone(element);
$(newElement).find('ul').remove();
categories.push(newElement);
});
return categories;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.