开发者

Using jQuery, select first word of element and alter css

开发者 https://www.devze.com 2023-03-16 16:46 出处:网络
I\'ve seen a lot of examples of how to take the first word of an element and add a span around it, giving that element a new class you can alter in CSS, but I have not been able to figure out how to j

I've seen a lot of examples of how to take the first word of an element and add a span around it, giving that element a new class you can alter in CSS, but I have not been able to figure out how to just alter the CSS directly in jQuery.

I'm using this code to do the span thing right now:

$("h1").html(function(i, text){
  return text.replace(/\w+\s/, function(match){
    return '<span class="first_word"> + match + '</span>;
}); });

I'm trying to make the first word of titles a new color and font-family. It works for my h1, but i also have a widget title h3 that displays the added span in plain text when I add it to the selection. So I want to just change the css of the first word instead of adding a span. (I also have no idea what "/\w+\s/" is doing so explaining that would be an 开发者_如何转开发added bonus :) )

Thank you wise ones!


There is a first-letter and a first-line pseudo element but there is no first-word. You need the span.


From what I understand you have 2 questions.

How can I modify the code above to make it works with H1 and H3 and the second question is about the regex /\w+\s/.

1) You can just use Jquery multiple selector:

$("h1, h3").html(function(i, text){
  return text.replace(/\w+\s/, function(match){
    return '<span class="first_word"> + match + '</span>;
}); });

For more documentation you can see JQuery Documentation for multiselector.

2) /\w+\s/ is a Regex Expression. It's three part expression. The first one is \w that represent any "word" character. It's a shortcut for : [a-zA-Z0-9_]. The second is the + that will let you have multiple [a-zA-Z0-9_]. It will group these characters to create a word and the last part is the \s that say to match the word until a space appear. You can get additionnal information about Regex Word Boundary in this Regex Documentation.


For first word changes.....

$('h1').each(function() {
var jqt = $(this);
var txt = jqt.text();
jqt.html('<span style="font-size:200%">'+txt.substring(0,(txt.indexOf(" ")))+'</span>'+ txt.substring((txt.indexOf(" "))));
});


Below script simply edits h1 content's HTML and surrounds words (the \w+ RegEx) with a span element.

jQuery(document).ready(function( $ ){
    
    $('h1').each(function(){
     var me = $(this);
     me.html(me.html().replace(/^(\w+)/, '<span>$1</span>'));
});

});

CSS

h1 span {
    font-weight: 400;
    color: red;
}


You can use the .css method. cf. http://api.jquery.com/css/

You may want something like

$(".first_word").css('color', 'red');

or so.

Also: /\w+\s/ is a regular expression saying a word followed by whitespace.

0

精彩评论

暂无评论...
验证码 换一张
取 消