Reputation: 11
I'd like to change
<h1>Headline Text - More Headline Text</h1>
to
<h1><span class="something">Headline Text</span> - More Headline Text</h1>
with jQuery.
First, I have to check, if there is a "-" in the h1-tag on the whole website. If there is, I'd like to insert the span-tag with a customized class BEFORE the "-". Otherwise just leave the h1-tag untouched.
Is this possible?
Thanks so much in advance!
Upvotes: 0
Views: 1225
Reputation: 1834
try this
$(document).ready(function(){
var controls =$('h1').html();
var g=controls.split("-");
if(g.length>1)
{
var texts='<span>'+g[0]+'</span> - '+g[1];
alert(texts);
$('h1').html(texts);
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<h1>Headline Text - More Headline Text</h1>
Upvotes: 2
Reputation: 74738
Try this:
$('h1').each(function() {
var found = $(this).text().indexOf('-') !== -1;
if (found) {
var arr = $(this).text().split('-');
$(this).html('<span class="something">' + arr[0] + '</span> - ' + arr[1]);
}
});
.something {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Headline Text - More Headline Text</h1>
<h1>Headline Text - More Headline Text</h1>
<h1>Headline Text</h1>
<h1>Headline Text - More Headline Text</h1>
Upvotes: 0
Reputation: 18883
Try This :-
$('h1').each(function(){
if($(this).html().indexOf("-") !== -1)
{
var html = $(this).html();
var newhtml = html.split("-")[0];
newhtml = "<span class='something'>"+ newhtml +"</span>"
$(this).html(newhtml + "- " + html.split("-")[1])
}
});
Upvotes: 0