I’m looking for a nice way to mark/select all elements between two selected elements.
Imagine
<parent>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
</parent>
There’s a click handler on parent. The user now can select two p element in this list an then all p-elements in between should get ‘activated’.
I’m thinking about a system like:
- first click: mark/remember first element -> A
- second click: mark/remember second element -> B
- determine whether or not A is before B
- do a A.nextUntil(B) (unless B is before A)
I have no idea how to do 3, expect the brute force approach (iterate in both directions and see if it is there)
- Does the dom internally know what element comes before another?
- Are there any nicer ideas?
About my situation: parent could contain several thousand p’s.
Thanks for your help/ideas!
Reto
To determine which element comes first you could simply do:
Or, a slightly faster approach:
Note, both of these approaches will only work properly if
aandbhave the same parent.How are the
<p>s added? Maybe you could give them each an ID corresponding to their position (e.g.p1,p2…) — this would definitely save you from having to determine their positions using the above approaches.