<p>Lorem Ipsum <a href="#">Link</a> <div ... </div> </p>
我想在不使用的情况下使用jQuery围绕'Lorem Ipsum',所以结果如下:
<p><span>Lorem Ipsum </span><a href="#">Link</a> <div ... </div> </p>
有什么想法吗?感谢
答案 0 :(得分:16)
首先,您需要某种方式来访问该段落。您可能希望为其指定id
属性,例如“foo”:
<p id="foo">Lorem Ipsum <a href="#">Link</a> <div ... </div> </p>
然后,您可以使用document.getElementById
访问该元素并根据需要替换其子元素:
var p = document.getElementById('foo'),
firstTextNode = p.firstChild,
newSpan = document.createElement('span');
// Append "Lorem Ipsum" text to new span:
newSpan.appendChild( document.createTextNode(firstTextNode.nodeValue) );
// Replace old text node with new span:
p.replaceChild( newSpan, firstTextNode );
为了使其更可靠,您可能希望在访问第一个子项之前调用p.normalize()
,以确保将锚点之前的所有文本节点合并为一个。
Oook,所以你想用一个元素替换一个文本节点的一部分。我就是这样做的:
function giveMeDOM(html) {
var div = document.createElement('div'),
frag = document.createDocumentFragment();
div.innerHTML = html;
while (div.firstChild) {
frag.appendChild( div.firstChild );
}
return frag;
}
var p = document.getElementById('foo'),
firstChild = p.firstChild;
// Merge adjacent text nodes:
p.normalize();
// Get new DOM structure:
var newStructure = giveMeDOM( firstChild.nodeValue.replace(/Lorem Ipsum/i, '<span>$&</span>') );
// Replace first child with new DOM structure:
p.replaceChild( newStructure, firstChild );
处理低级别的节点是一个令人讨厌的情况;特别是没有任何抽象来帮助你。我试图通过从替换的“Lorem Ipsum”短语产生的HTML字符串中创建DOM节点来保持正常感。纯粹主义者可能不喜欢这种解决方案,但我发现它非常合适。
编辑:现在使用文档片段!谢谢 Crescent Fresh !
答案 1 :(得分:1)
<强>更新强>
下面的方法将搜索由container
为首的子树,并在span元素中包装text
的所有实例。这些单词可以出现在文本节点中的任何位置,文本节点可以出现在子树中的任何位置。
(好的,所以只需要进行一些小的调整。:P)
function wrapText(container, text) {
// Construct a regular expression that matches text at the start or end of a string or surrounded by non-word characters.
// Escape any special regex characters in text.
var textRE = new RegExp('(^|\\W)' + text.replace(/[\\^$*+.?[\]{}()|]/, '\\$&') + '($|\\W)', 'm');
var nodeText;
var nodeStack = [];
// Remove empty text nodes and combine adjacent text nodes.
container.normalize();
// Iterate through the container's child elements, looking for text nodes.
var curNode = container.firstChild;
while (curNode != null) {
if (curNode.nodeType == Node.TEXT_NODE) {
// Get node text in a cross-browser compatible fashion.
if (typeof curNode.textContent == 'string')
nodeText = curNode.textContent;
else
nodeText = curNode.innerText;
// Use a regular expression to check if this text node contains the target text.
var match = textRE.exec(nodeText);
if (match != null) {
// Create a document fragment to hold the new nodes.
var fragment = document.createDocumentFragment();
// Create a new text node for any preceding text.
if (match.index > 0)
fragment.appendChild(document.createTextNode(match.input.substr(0, match.index)));
// Create the wrapper span and add the matched text to it.
var spanNode = document.createElement('span');
spanNode.appendChild(document.createTextNode(match[0]));
fragment.appendChild(spanNode);
// Create a new text node for any following text.
if (match.index + match[0].length < match.input.length)
fragment.appendChild(document.createTextNode(match.input.substr(match.index + match[0].length)));
// Replace the existing text node with the fragment.
curNode.parentNode.replaceChild(fragment, curNode);
curNode = spanNode;
}
} else if (curNode.nodeType == Node.ELEMENT_NODE && curNode.firstChild != null) {
nodeStack.push(curNode);
curNode = curNode.firstChild;
// Skip the normal node advancement code.
continue;
}
// If there's no more siblings at this level, pop back up the stack until we find one.
while (curNode != null && curNode.nextSibling == null)
curNode = nodeStack.pop();
// If curNode is null, that means we've completed our scan of the DOM tree.
// If not, we need to advance to the next sibling.
if (curNode != null)
curNode = curNode.nextSibling;
}
}
答案 2 :(得分:0)
结合这两个教程:
PPK on JavaScript: The DOM - Part 3
基本上你需要访问节点值,删除它,并创建一个新的子元素,其节点值是父项的节点的值,然后将该元素(在这种情况下为span)附加到父元素(此处的段落)情况下)
答案 3 :(得分:0)
如何在javascript中使用正则表达式并将“Lorem Ipsum”替换为“&lt; span&gt; Lorem Ipsum&lt; / span&gt;” (只记得你必须得到元素的“innerHTML”,然后再次替换整个批次,这可能有点慢)