Amit Shah Amit Shah - 4 months ago 39
HTML Question

jQuery: How to select text between two closed html tags

I am trying to wrap the intro/help text in html document using jQuery.It is not inside any tag but between two closed html tags.

Please see attached code snippet for example. the 2nd end tag can also be other than

<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>




Answer

The nextUntil() method not selects textnodes.

You can get the text node by nextSibling property of node and get text content by textContent property of text node.

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);
<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>


If you want to wrap the element by a p tag then do it like.

$($('b.page-title')[0].nextSibling).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>


If it contains br tag and you want to include it as a text then do it like.

var get = false;

$($('b.page-title').parent().contents().filter(function() {
  if ($(this).is('b.page-title')) {
    get = true;
    return false
  }
  if ($(this).is('p'))
    get = false;
  return get;
})).wrapAll('<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<br/> and wrap it in new P-Tag
<p align="center">This can by any html tag</p>