Reputation: 143
I am back and forth with this but I think I am so close. I want to wrap the last character of all H1 tags in a div with class .content if it is a full stop or question mark (to apply color). Here is what I have:
$(function() {
$('.content h1').each(function() {
last = $(this).text().trim().slice(-1);
if(last === '.' || last === '?') {
alert(last);
//last.wrap('<span class="orange-end"></span>');
}
});
});
This will alert the last character correctly, I am just struggling to wrap and return.
Cheers all.
Upvotes: 0
Views: 195
Reputation: 24965
$(function() {
$('.content h1').each(function() {
// get the text
var text = this.innerHTML.trim();
//do logic if the last character is a period or question mark
if (['.', '?'].indexOf(text.slice(-1)) > -1) {
// set the html back to what it was, replacing the last
// character with the wrapped html
this.innerHTML = text.slice(0, -1)
+ '<span class="orange-end">'
+ text.slice(-1)
+ '</span>';
}
});
});
.orange-end { color: orange; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="content">
<h1>What is the meaning of this?</h1>
<h1>No way!</h1>
<h1>I know.</h1>
</div>
Upvotes: 2