Evan
Evan

Reputation: 3501

Wrap the first word in span after the last link jQuery

Trying to find a way to wrap the first word in a span tag. The text to wrap would always trail the last link

 <div class="style1">
    <a class="style2" href="http://www.example.com">a</a>
    <a class="style3" href="http://www.example.com">b</a>
    test test test test test test test 
</div>

I'd like the first test to be wrapped in <span>test</span>

It would be used in a more in depth solution here

Fiddle: http://jsfiddle.net/evanmoore/awwTA/1/

Upvotes: 1

Views: 268

Answers (2)

Ram
Ram

Reputation: 144689

$('.pag').contents().filter(function () {
  // IE doesn't support `textContent` proerty, you can replace it with $(this).text()
  if (this.nodeType === 3 && $.trim(this.textContent) !== '') {
      $(this).wrap('<div/>').parent().html(function (i, v) {
           return v.replace(/(\w+\s)/, '<span>$1</span>')
      }).replaceWith(function() {
           return this.innerHTML;
      })
  }
})

http://jsfiddle.net/XKjtq/

Upvotes: 2

ATOzTOA
ATOzTOA

Reputation: 35950

Try this bit of code:

<script>
    data = $(".style1").html().trim().split("\n");
    str = data[data.length - 1];
    data.splice(data.length - 1, 1);
    str = str.trim().split(" ");
    str[0] = "<span>" + str[0] + "</span>";
    data[data.length] = str.join(" ");
    $(".style1").html(data.join("\n"));
</script>

Upvotes: 0

Related Questions