javascriptjqueryhtmlnextsibling

How to wrap string which is sibling to strong tag in new tag using jquery?


In an html like the sample below, I need to wrap the text I need to select part in a span tag with a custom class, but how do I select just that part excluding the content in the strong tags above it, using jquery?

<span>
  <strong> random gibberish </strong>
  text I need to select
</span>

Edit: simply using .text() on parent won't work because that converts the whole inner html to text including the part in strong


Solution

  • You can use contents and eq functions:

    $('span').each(function() {
      $(this).contents().eq(2).wrap('<span class="someClass"/>')
    });
    .someClass {
    color: red;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <span>
      <strong> random gibberish </strong>
      text I need to select
    </span>