I have a problem with first word when is as link, word appears not normal.
$('h3')
.each(function () {
var h = $(this).html();
var index = h.indexOf(' ');
if (index == -1) {
index = h.length;
}
$(this).html('<span style="color:#fff;">' + h.substring(0, index) + '</span>' + h.substring(index, h.length));
});
And when not appear the link in the h3 tag looks good
Try something like this instead: http://jsfiddle.net/jnmwyagy/2/
<h3><a href="#">google</a><p><span class="text">First</span> Word</p></h3>
<h3><a href="#">google</a><p><span class="text">First</span> Word</p></h3>
jQuery
$('h3')
.each(function () {
$(this).find('.text').css("color", "red");
});
Try to search for opening a
tags, not for spaces.
$('h3').each(function () {
var h = $(this).html();
var index = h.indexOf('<a');
if (index == -1) {
index = h.length;
}
$(this).html('<span style="color:#fff;">' + h.substring(0, index) + '</span>' + h.substring(index, h.length));
});
And seriously, it would be better just to apply CSS styles for h3
and a
tags.
You cannot use color in span element to set color in a tag. You need to set the color in a tag itself:
$('h3').each(function () { if($(this).contents().first().is('a')){ $(this).contents().first().css('color','#fff'); }else { var node = $(this).contents().filter(function(){ return this.nodeType == 3; }).first(); var text = node.text(); var first = text.slice(0, text.indexOf(" ")); node[0].nodeValue = text.slice(first.length); node.before('<span style="color:#fff">' + first + '</span>'); } });
h3{ background: #f00; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <h3><a>test</a> word</h3> <h3>test word</h3>
Code for first word selector taken from here .
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.