The answer jQuery - wrap all unwrapped text in p tags gives a jquery solution that wraps all text nodes with an html tag. I am wondering how to do it without jquery (if possible).
-
1Have you tried it yet? Where are you stuck? Please show us your attempt.Bergi– Bergi2013年11月08日 00:04:53 +00:00Commented Nov 8, 2013 at 0:04
-
Have a look at stackoverflow.com/questions/15958020/…plalx– plalx2013年11月08日 00:14:31 +00:00Commented Nov 8, 2013 at 0:14
-
how is this offtopic, it's about javascript and asking a javascript questionKJW– KJW2013年11月08日 06:50:30 +00:00Commented Nov 8, 2013 at 6:50
2 Answers 2
Here you go: http://jsfiddle.net/reWXX/14/
var textnodes = getTextNodesIn(document.getElementById('demo'));
for(var i=0; i < textnodes.length; i++){
if (textnodes[i].parentElement.id === 'demo') { // This is redundant
var newNode = document.createElement('p');
newNode.textContent = textnodes[i].nodeValue;
textnodes[i].parentNode.replaceChild(newNode, textnodes[i]);
}
}
This is in plain JavaScript. However if Markasoftware works, IMHO that would be the proper way to do it, with a TreeWalker.
2 Comments
getTextNodesIn?Here's a way:
var walker=document.createTreeWalker(document.body,NodeFilter.SHOW_TEXT,null,false);
while(walker.nextNode()){
var newNode=document.createNode('p');
newNode.textConTent=walker.currentNode.textContent;
walker.currentNode.parentNode.replaceChild(newNode,walker.currentNode);
}
I haven't tested it yet and I've never used a treeWalker before, but I think this should work fine. I'm not sure, however, if the while loop MIGHT skip the first text node in the document. You'll just have to try.