I have the following html document that is auto generated by a third party :
<body>
<pre>
<b>Field1</b> something
<b>Field2</b> something else
...
</pre>
</body>
I want to eventually highlight the text that comes after the text that is bolded under certain circumstances, so I opted to use greasemonkey for that.
Since that text doesn't have any id associated with it, I was thinking of recreating the page and between</b>
and <b>
I will surround all the text with a mark tag with the ID being the text of the field before it, like so:
<body>
<pre>
<b>Field1</b> <mark id=Field1>something </mark>
<b>Field2</b> <mark id=Field2>something else </mark>
...
</pre>
</body>
Is there an easy way to achieve this without having to recreate the page? e.g inserting elements after each of the tags?
Using plain JS, you can select all the b
nodes, loop over it, and in each iteration, replace the sibling text node with new mark
node.
Check the working example below:
document.querySelectorAll('b').forEach(b => {
let textNode = b.nextSibling;
let newNode = document.createElement('mark');
newNode.id = b.innerText;
newNode.innerHTML = textNode.textContent;
textNode.replaceWith(newNode);
})
<pre>
<b>Field1</b> something
<b>Field2</b> something else
</pre>