如何使用您无法控制标记的元素来包装文本?

时间:2015-03-03 23:37:51

标签: jquery

所以我正在开发一个我无法控制标记的功能。我想在某些文本中添加填充,但问题是它没有我可以定位的容器元素。如果我定位.content-header并添加填充,则填充该div中的所有内容,这不是我想要的。标记看起来像这样。如何用<p>元素包装文本?

<div class="content-header">
  <div class="element"><img src="img.png"></div>
  "Text that I want to wrap in an element"
</div>

2 个答案:

答案 0 :(得分:1)

您可以使用.contents()获取所有节点;然后,filter 非空文本节点并包装:

$('.content-header')
  .contents()
  .filter(function() {
    // we're only interested in text nodes that are not empty
    return this.nodeType == 3 && $.trim(this.nodeValue).length;
  })
  .wrap('<p>');

Demo

答案 1 :(得分:0)

您可以只过滤文本(nodeType = 3),然后将其包装在p标记中。 见下文:

$('.content-header').contents().filter(function(){
   return this.nodeType === 3;
}).wrapAll("<p class='red' />");
.red { color: red; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="content-header">
  <div class="element"><img src="http://i.stack.imgur.com/6UgUs.jpg?s=32&g=1"></div>
  "Text that I want to wrap in an element"
  <span>Another text in span</span>
</div>