Runerbex
Runerbex

Reputation: 33

How to wrap sibling text of elements with tag using javascript/jquery?

I would like to transform:

<span class="element">
  <span class="word">The</span>
  <span class="word">car</span>
  <span class="word">speed</span>
  <span class="word">was</span>
  40km/s
</span>  

into:

<span class="element">
  <span class="word">The</span>
  <span class="word">car</span>
  <span class="word">speed</span>
  <span class="word">was</span>
  <span class="data">40km/s</span>
</span>  

How could I change it using javascript or jquery?

Upvotes: 0

Views: 43

Answers (1)

Mohammad
Mohammad

Reputation: 21489

You need to use .contents() and .last() to select target text from end of .element and use .wrap() to wrap it with span tag.

$(".element").contents().last().wrap("<span class='data'></span>");
.data{color:blue}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="element">
  <span class="word">The</span>
  <span class="word">car</span>
  <span class="word">speed</span>
  <span class="word">was</span>
  40km/s
</span>

Upvotes: 2

Related Questions