I have some HTML that looks roughly like this:
<div>
<p>Herp derpsum sherper herpy derpus jerpy berps cerp terpus.
Derpy merpus <a name="a1start" type="start"></a>pee derpler berps! Perp
sherper herp terp herpy derpler.</p>
<p>Sherper merp herpler herp pee. Derpler terpus, mer re berp
der perp se?<a name="a2start" type="start"></a> Ze ter derps tee! Herpsum derp
sherper ler merp derperker <a name="a3start" type="start"></a>jerpy derpler
herderder zerpus.</p>
</div>
<div>
<p>Derp sherper perper tee. Derperker
zerpus ner cerp terpus herpy sherpus sherp. Perp derp pee serp herp
zerpus herpem herderder derpler berp! Merpus derpy <a name="a1end" type="end"></a>
herpler sherp derps perper derperker derp dee der. Merpus der
derps, <a name="a2end" type="end"></a>derpus herpderpsmer! Derp merp er sherpus dee perp herpy derpsum
perper pee. Herpler derpsum me sherlamer ler derpler derpy. Cerp de
perper derpy. Le herderder herpler re ter. Serp ze derperker re. Terp
berps terpus ter, er perp derpsum. </p>
<a name="a3end" type="end"></a>
</div>
In other words, anchors used to mark starts and ends of highlighted areas. They are irrespective of their locations in <div>
or other containers. The highlights are overlapping, thus a1start
corresponds to a1end
.
I'm trying to figure out a way to highlight them, going from start anchors to end anchors, and ignoring all the HTML in between. So, one highlight from a1start
to a1end
. Another, overlapping highlight from a2start
to a2end
, and so on.
Note again that these are overlapping, so I can't just use spans, because then how would a given </span>
know that it's the end of, e.g., a2
rather than a closer one at a1
?
In other words, think of this structure:
<highlightA>
Here is something highlighted in A.
<hightlightB>
Here is something highlighted in A and B.
</hightlightA>
Here is something only highlighted in B.
</hightlightB>
Here is something not highlighted.
I would usually just transform these <a>
tags to <span>
and </span>
, and then highlight them with CSS: span { background-color: yellow }
. But that would produce overlapping tag sets, no? Which is illegal in the HTML/XML world?
So I need to use JavaScript to identify these markers, figure out which ones match, and highlight those spans of text, without trying to edit the HTML. In other words, I need to overlay some highlighting on top of the page, without messing with this markup.
I'm a JavaScript beginner, so go easy on me, please.
Edit: Here's a Codepen I put together which illustrates this problm a little better, and tries to implement the (non-working) solution below. It uses different highlight colors to show how the overlapping highlights aren't working.
from How can I select text between anchors and highlight them as such?
No comments:
Post a Comment