2017-08-29 23 views
0

如何从下面的元素中获取“跟随”类别下的所有名称。名称的排列方式对我来说有点陌生,这就是为什么我无法获得所有这些名称的原因。我已经使用了一个能够抓住第一个选择器的选择器。但是,我希望所有名称都在“后面跟着”标题下,直到“edited_into”标题。提前致谢。无法创建合适的选择器来抓取名称

这里的元素在其中所需要的名字是一个链接: https://www.dropbox.com/s/nzmvfc75szlgyyn/elements%20for%20expression.txt?dl=0

的选择我已经试过:

a#followed_by+h4.li_group+div.odd a 

我有,结果只有第一个名字:

Star Trek V: The Final Frontier 

顺便说一句,我唯一的意图是解析名称使用此选择器不风格。

回答

1

您拥有的选择器几乎是正确的。

a#followed_by+h4.li_group ~ div.soda a 

~作品不同,以在其将选择选择器的第一部分之后的任何匹配元件的+,而+将仅选择紧接在选择器的第一部分以下元件。 当然,“第一部分”我指的是a#followed_by+h4.li_group

我也改变了选择器找到div.soda而不是div.odd,所以你得到所有相关的元素,而不是只是奇数。


因为这样的CSS选择器的工作,我们不能问“仅元素,直到edited_into”。但是,我们可以使用JavaScript解决此问题。

简单的for循环与条件break将是最简单的方法。

var titles = []; 
var items = document.querySelectorAll('a#followed_by+h4.li_group ~ div.soda a'); 
//firstEditedIntoItem represents the first element in 
//the `edited_into` section. If it's null, then there 
//is none, and we have nothing to worry about. 
var firstEditedIntoItem = 
    document.querySelector 
    ('a#edited_into+h4.li_group+div.soda a, a#spin_off_from+h4.li_group+div.soda a'); 
    // Note: This selector will find the first instance that matches any of the 
    // specified sections. You could add another and replace `spin_off_from` with 
    // another section id. 
for(var i=0; i<items.length; i++) { 
    var it = items[i]; 
    //don't accept elements after 'edited_into' 
    // If firstEditedIntoItem is null, it will not match either. 
    if(it==firstEditedIntoItem) break; 
    titles.push(it.textContent); 
} 
console.info(titles.join('\n')); 
+0

感谢您的解决方案。使用你的选择器,我得到了“后面跟着”标题的所有名字,这部分是我想要的。不过,我的意图是从标题开始,然后一找到“edited_into”标题就停下来。否则,它会抓住所有人。也许你没有注意到我在上面的描述中也提到了它。再次感谢迈克。 – SIM

+0

哦,当然 - 你是对的我错过了那部分,不知何故。单纯用CSS来做这件事是不可能的 - 除非我错过了一些东西。假设JS没问题,在遇到“edited_into”部分之后的第一个元素后,可以停止处理列表。如果您有兴趣,我可以用一些示例代码更新答案。 – mike

+0

非常感兴趣。顺便说一句,我接受你的答案。希望你会编辑你提供的部分。 – SIM