I am trying to change first color of define class or tag by using jquery. Things work fine but I have one title having own span and giving trouble. I am using below code to add span element and inline style for first word.
$(document).ready(function()
{
$('.header-logo, h1').each(function() {
var h = $(this).html();
var index = h.indexOf(' ');
if(index == -1) {
index = h.length;
}
$(this).html('<span style="color:black;">' + h.substring(0, index) + '</span>' + h.substring(index, h.length));
});
});
This is adding span tag perfectly and change the color too. But I have one title with below html structure
<h1>
<span id="fav" class="btn-fav"><a href="#"Add to fav</a></span>
<span class="the-title">Title text goes here</span>
</h1>
Here I want to add color only for “Title text goes here” first word (Title) but the javascript breaking structure by adding another span tag into the span tag something like below
<span style="color:black;">
<span< span=""> class="btn-fav id="fav">.....
So how can I resolve this issue?
You can use
htmlmethod,htmlaccepts a function, you can find the first word and wrap it byspanelement.http://jsfiddle.net/AuKWT/
Note that you should fix your markup: