I am writing a Greasemonkey script in which in one place I’m converting all the spaces in the text into <br> so that the string appears more vertical in its cell in the table.
The HTML that I’m matching is:
<span>
<img class="icon itemicon" alt="Manual item" ...etc...>
Chapter 2 reading
<a title="Sort in descending order" href="index.php....."> etc </a>
</span>
Here is my code:
var child = spanelm.firstChild;
var textChild = child.nextSibling;
textChild.textContent = textChild.textContent.replace(/ /g, "<br>");
My Greasemonkey script is finding the right element and doing the change successfully, but on the web page I see the <br> tags literally:
Chapter<br>2<br>reading
(In another place in my code, I’m doing a similar thing, which seems to work:
spanelm.firstChild.innerHTML = spanelm.firstChild.text.replace(/ /g, "<br>");
but I cannot get that to work in this case, with this organization of the HTML.)
I feel like I need to tell Greasemonkey to eval() the HTML or something…
A text node doesn’t have an
innerHTML, so you can’t insert new tags that way. (You should be very careful about this kind of string-replace of any node usinginnerHTML— it’s only a matter of time before the code trashes nested elements, inline JS, attached event handlers, etc.)To insert tags in a text element, you need to break up that element into new text elements, interspersed with the tags you desire. In this case, replacing each run of spaces with a
<br>would use code like this:(See it in action at jsFiddle.)