简体   繁体   English

组选定元素:document.querySelectorAll

[英]Group Selected Elements: document.querySelectorAll

Hi how can I group my document.querySelectorAll if I have a case like this: 嗨,如果我遇到这样的情况,如何将我的document.querySelectorAll分组:

<div>
 <p class="flower">Flower 1</p>
 <p class="bee">Bee 1</p>
 <p class="tree"></p>
</div>

<div>
 <p class="flower">Flower 2</p>
 <p class="dude"></p>
 <p class="snow-leopard"></p>
</div>

<div>
 <p class="flower">Flower 3</p>
 <p class="tree"></p>
 <p class="mountain"></p>
 <p class="wizard"></p>
 <p class="bee">Bee 3</p>
</div>

I always want to select the flower, if there is a bee I want to have it attached to the flower, I don't care about the rest. 我一直想选择花朵,如果有一只蜜蜂要把它附着在花朵上,其余的我就不在乎了。 The flowers and bees don't have a specific order in the div and there are cases with no bee. 花朵和蜜蜂在div中没有​​特定顺序,并且有些情况下没有蜜蜂。 Also assume that there is a class at the flower and bee but the rest of the structure isn't as clean as in the example. 还假设花朵和蜜蜂上有一个类,但是结构的其余部分不像示例中那样干净。 The only solution I have so far is to go a few levels up and then use regex. 到目前为止,我唯一的解决方案是先升级几个级别,然后再使用正则表达式。 At the end I want to include them both into a json: 最后,我想将它们都包含到json中:

[{flower: "yellow", bee:"bumblebee"},...]

This approach: 这种方法:

var flowers = document.querySelectorAll(flower);
var bees = document.querySelectorAll(bee);

And then iterating afterwards over the both arrays does not work. 然后在两个数组上进行迭代不起作用。

The problem is that you can't really match the flowers with the bees simply with CSS selectors. 问题在于,仅使用CSS选择器就无法真正将花朵与蜜蜂匹配。 You need to iterate over all flowers and find the bee sibling if there is one. 您需要遍历所有花朵,如果有则寻找蜜蜂的兄弟姐妹。 One way to do this is to get the parent of a flower and then look for bees. 一种方法是获取花朵的亲本,然后寻找蜜蜂。

var obj = Array.prototype.map.call(document.querySelectorAll(".flower"), function(f){
    var node = {flower: f.textContent};
    var bee = f.parentNode.querySelector(".bee");
    if (bee) {
        node.bee = bee.textContent;
    }
    return node;
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM