jQuery:如何在两个已关闭的html标记之间选择文本

时间:2016-07-19 06:21:06

标签: javascript jquery html

我正在尝试使用jQuery在html文档中包装intro / help文本。它不在任何标记内,而是在两个封闭的html标记之间。

请参阅附件中的代码段。第二个结束标记也可以不是<p>

var txtHelp = jQuery('b.page-title').nextUntil('p').text();
console.log(txtHelp);

//jQuery('b.page-title').nextUntil('p').text().wrap("<p />");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<b class="page-title"><h4>System Log</h4><hr class="text-primary"></b>
How to select this text and wrap it in new P-Tag
<p align="center">This can by any html tag</p>

2 个答案:

答案 0 :(得分:8)

nextUntil() 方法不会选择文字节点。

您可以通过节点的 nextSibling 属性获取文本节点,并通过文本节点的 textContent 属性获取文本内容。

&#13;
&#13;
var txtHelp = jQuery('b.page-title')[0] // get the dom object
  .nextSibling // get the text node next to it
  .textContent; // get text content
console.log(txtHelp);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<b class="page-title"><h4>System Log</h4><hr class="text-primary"></b>
How to select this text and wrap it in new P-Tag
<p align="center">This can by any html tag</p>
&#13;
&#13;
&#13;

更新1:如果你想用p标签包装元素,那么就这样做。

&#13;
&#13;
$( // wrap by jquery to convert to jQuery object
  $('b.page-title')[0] // get the dom element also you can use `get(0)`
  .nextSibling // get the textnode which is next to it
).wrap('<p/>'); //  wrap the element by p tag
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<b class="page-title"><h4>System Log</h4><hr class="text-primary"></b>
How to select this text and wrap it in new P-Tag
<p align="center">This can by any html tag</p>
&#13;
&#13;
&#13;

更新2 :如果它包含br标记,并且您希望将其作为文本包含,那么请使用 contents() 方法执行一些棘手的操作。

&#13;
&#13;
var get = false;

$($('b.page-title')
  .parent() // get it's parent
  .contents() // get all children node including text node
  .filter(function() {
    if ($(this).is('b.page-title')) {
      get = true; // if element is 'b.page-title' then set flag true , we need to get element from here
      return false // return false that we don't need the 'b.page-title'
    }
    if ($(this).is('p')) // check element is `p`, that we need to get element uptop tag
      get = false; // update flag
    return get; // return the flag for filtering
  })).wrapAll('<p/>'); // use wrapAll to wrap all elements withing single tag
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<b class="page-title"><h4>System Log</h4><hr class="text-primary"></b>
How to select this text
<br/>and wrap it in new P-Tag
<p align="center">This can by any html tag</p>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

对于纯jQuery方法,您可以尝试:

var contents = $('b.page-title').contents(),
    textNodes = contents.filter(function() { return this.nodeType === 3; });

console.log(textNodes[0].textContent);

请参阅resource property