How to insert `<span id="myspanid"></span>` to all content between html tags?
Fore example, I want to change
<h1>content1</h1><p>content2&l开发者_StackOverflowt;/p>
to
<h1><span id="myspanid">content1</span></h1><p><span id="myspanid">content2</span></p>
I prefer to do this at server side with php.
If you're using jQuery:
$('body *').wrap('<span class="foo"></span>');
If you're not (to fix @minitech's code):
var elts = document.body.childNodes,
numElts = elts.length,
elt;
for(var i = 0; i < numElts; i++) {
elt = elts[i];
elt.innerHTML = '<span class="foo">' + elt.innerHTML + '</span>';
}
Don't use innerHTML the way suggested in other answers, it will mess with whatever else you have in the element. You need to look for text nodes and wrap them, like this:
// Pass either an id or a DOM element
var wrapContent = (function() {
// This could be passed as a parameter
var oSpan = document.createElement('span');
oSpan.className = 'mySpanClass';
return function(id) {
var el = (typeof id == 'string')? document.getElementById(id) : id;
var node, nodes = el && el.childNodes;
var span;
var fn = arguments.callee;
for (var i=0, iLen=nodes.length; i<iLen; i++) {
node = nodes[i];
if (node.nodeType == 3) {
span = oSpan.cloneNode(false);
node.parentNode.insertBefore(span, node);
span.appendChild(node);
} else {
fn(node);
}
}
}
}());
If you want to run it on a string of HTML, then create a div, insert the string as its innerHTML, run the above function passing it the div, then grab the innerHTML back:
function wrapHTMLstring(s) {
var el = document.createElement('div');
el.innerHTML = s;
wrapContent(el);
return el.innerHTML;
}
alert(wrapHTMLstring('<h1>content1</h1><p>content2</p>'));"
// <h1><span class="mySpanClass">content1</span></h1><p><span class="mySpanClass">content2</span></p>
Note that the childNodes collection will differ in different browsers for the same HTML if you have any extra whitespace, so you may need to do some processing there (e.g. if a textNode doesn't have any content, don't wrap it).
If you're not (fixed to 'do it on a string', hopefully):
var b = document.body.childNodes;
for(var i = 0; i < b.length; i++) {
if(b[i].nodeType === 1) {
b[i].innerHTML = '<span class="foo">' + b[i].innerHTML + '</span>';
} else if(b[i].nodeType === 3) {
var newElement = document.createElement('span');
newElement.className = "foo";
b.replaceChild(newElement, b[i]);
}
}
精彩评论