[英]How do to wrap a span around a section of text without using jQuery
<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>
有任何想法嗎? 謝謝
首先,您需要某種方式來訪問該段落。 你可能想給它一個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 !
更新:下面的方法將搜索以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;
}
}
結合這兩個教程:
基本上你需要訪問節點值,刪除它,並創建一個新的子元素,其節點值是父項的節點的值,然后將該元素(在這種情況下為span)附加到父元素(在本例中為段落)
如何在javascript中使用正則表達式並將“Lorem Ipsum”替換為“<span> Lorem Ipsum </ span>”(請記住,您必須獲取元素的“innerHTML”,然后再次替換整個批次可能有點慢)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.