Manipulating a DOM node containing text and other nodes with other than innerHTML
I'd like to know if there is a way to copy DOM nodes so that one can both slice the textual part of a node and keep the nodes contained within that node intact. I have a function that takes a paragraph, separates the first letter from it, then creates a new node, adds to it that letter wrapped in a new node, then inserts the rest of the text. The trouble is, when that paragraph contains other HTML elements they get flattened to a string because I extract the text using innerHTML. I need them to remain DOM nodes. Here's the function:
function crea开发者_Go百科teDropCappedParagraph(article) {
pars = article.getElementsByTagName("p");
first_par = pars[0];
var text = first_par.innerHTML;
text = text.trim();
var first_letter = text.substr(0,1)
text = text.slice(1);
var t = document.createTextNode(text);
var dropcap = document.createElement("span");
dropcap.className = "dropcap";
dropcap.innerHTML = first_letter
var dcpar = document.createElement("p");
dcpar.style.position = "relative";
dcpar.appendChild(dropcap);
dcpar.appendChild(t);
article.insertBefore(dcpar, pars[0]);
article.removeChild(pars[1]);
}
and here's what it looks like when this effect is applied, notice the flattened a href links in the first paragraph:
http://legibilis.heroku.com/start-here
Thanks, James
Your problem is that you use this string to create a TextNode
, and therefore all special characters (such as <, >, ", etc.) get escaped (meaning they are converted to their safe counterparts: <
, >
, "
, etc.).
Here's an idea for a simple workaround:
Instead of creating a TextNode
called t, create a normal HTML node called t. For example, make this a 'div' tag. Then, modify this tag's .innerHTML
field: t.innerHTML = text;
. This shouldn't escape the content, AFAIK, and the div tag shouldn't bother you much (it's inline by default).
EDIT:
If you're using jQuery, $(text)
will give you the jQuery element (or elements) for the content of text
.
It worked, thank you:
function createDropCappedParagraph(article) {
pars = article.getElementsByTagName("p");
first_par = pars[0];
var text = first_par.innerHTML;
text = text.trim();
var first_letter = text.substr(0,1)
text = text.slice(1);
var t = document.createElement("span");
t.innerHTML = text;
var dropcap = document.createElement("span");
dropcap.className = "dropcap";
dropcap.innerHTML = first_letter
var dcpar = document.createElement("p");
dcpar.style.position = "relative";
dcpar.appendChild(dropcap);
dcpar.appendChild(t);
article.insertBefore(dcpar, pars[0]);
article.removeChild(pars[1]);
}
精彩评论