I’m attempting to select substrings–the character count, in square brackets–within several paragraphs and wrap each of them in <span> tags with a class, char_count, applied. Here’s the HTML for one, and the CSS:
var select_p = $('div#promo_area div.featured_box p');
select_p.each(function() {
var first_index = $(this).html().indexOf('[');
var last_index = $(this).html().indexOf(']') + 1;
var selected_text = $(this).html().substring(first_index, last_index);
selected_text.wrap('<span class="char_count" />');
});
span.char_count {
padding-top: 0;
color: #ff6600 !important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="promo_area">
<h3>Featured Stories</h3>
<div class="featured_box">
<h4><a href="/give">Senectus et Netus</a></h4>
<div>
<a href="/give"><img width="207" height="139" src="http://myrussreid.com/files/2011/06/ffffff1395-207x139.jpg" class="attachment-wds_home_image wp-post-image" alt="ffffff139" title="ffffff139" /></a>
</div>
<p>Pellentesque habitant morbi tristique senectus et netus. [100 characters w/spaces]</p>
<a href="/give">Please Give</a>
</div>
<!-- end .featured_box -->
</div>
It seems to work right up until the .wrap line—I get the correct substring in selected_text. The wrap itself doesn’t work. What stupid little thing am I doing wrong? Or is it a stupid BIG thing?
Here‘s my fiddle.
You could try implementing a solution using ranges and
surroundContentsif you’re feeling adventurous, or you could use this plugin to make it as easy as:Here’s a working fiddle: http://jsfiddle.net/Kpn7b/2/