简体   繁体   中英

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?

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM