简体   繁体   中英

Group Selected Elements: document.querySelectorAll

Hi how can I group my document.querySelectorAll if I have a case like this:

<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. 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:

[{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. 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;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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