我在HTML文档中有一些文字,如此......
<p> MY TEXT </p>
我希望在某个JS函数被触发时替换...
<p>
使用
<p><span class="auto-style1">
和...
</p>
使用
</p></span>
所以......我怎么做?
(更高级......)
然后我希望能够重复这个JS代码来替换所有<p>
和&amp; </p>
的...
那我该怎么做?
答案 0 :(得分:5)
因为问题被标记为jQuery ......
$('p').wrapInner('<span class="auto-style1"></span>');
答案 1 :(得分:0)
像这样:
$('p').html(function () {
return $( '<span/>' ).addClass( 'auto-style1' ).html( $( this ).html() )
});
答案 2 :(得分:0)
你可以像这样使用POJS。
CSS
.auto-style1 {
border-style: solid;
border-width: 2px;
}
HTML
<p>text1</p>
<div>
<p>text2</p>
<div>
<p>text3</p>
</div>
</div>
<p>text4</p>
<p>text5</p>
的Javascript
function wrapContent(element, tagName, wrapperTagName, wrapperProperties) {
wrapperProperties = wrapperProperties || {};
var tags = element.getElementsByTagName(tagName),
tagsLength = tags.length,
tagsIndex,
tag,
child,
wrappedContent,
prop;
for (tagsIndex = tagsLength - 1; tagsIndex >= 0; tagsIndex -= 1) {
tag = tags[tagsIndex];
child = tag.firstChild;
wrappedContent = document.createElement(wrapperTagName);
for (prop in wrapperProperties) {
if (wrapperProperties.hasOwnProperty(prop)) {
wrappedContent[prop] = wrapperProperties[prop];
}
}
while (child) {
wrappedContent.appendChild(child);
child = child.nextSibling;
}
tag.appendChild(wrappedContent);
}
}
wrapContent(document.body, "p", "span", {
"className": "auto-style1"
});
在 jsfiddle
上