繁体   English   中英

如何在不使用jQuery的情况下围绕一段文本包装span

[英]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;
  }
}

结合这两个教程:

JavaScript上的PPK:DOM - 第3部分

向DOM添加元素

基本上你需要访问节点值,删除它,并创建一个新的子元素,其节点值是父项的节点的值,然后将该元素(在这种情况下为span)附加到父元素(在本例中为段落)

如何在javascript中使用正则表达式并将“Lorem Ipsum”替换为“<span> Lorem Ipsum </ span>”(请记住,您必须获取元素的“innerHTML”,然后再次替换整个批次可能有点慢)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM