-4

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).

asked Nov 7, 2013 at 23:59
3
  • 1
    Have you tried it yet? Where are you stuck? Please show us your attempt. Commented Nov 8, 2013 at 0:04
  • Have a look at stackoverflow.com/questions/15958020/… Commented Nov 8, 2013 at 0:14
  • how is this offtopic, it's about javascript and asking a javascript question Commented Nov 8, 2013 at 6:50

2 Answers 2

1

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.

answered Nov 8, 2013 at 0:23
Sign up to request clarification or add additional context in comments.

2 Comments

what is getTextNodesIn?
Gets text nodes function. I thought its too big to post it here. Please look in the jsfiddle.net/reWXX/14. I've just rewrite what I got.
1

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.

answered Nov 8, 2013 at 0:15

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.