简体   繁体   中英

Apply different styles to parts of the same element using jQuery

Consider this element:

Count Dracula: Bleh bleh bleh

I need to split the text in a way that the bit before (and including) the colon has one style (say, bold and red) and the rest has another (say, black and italics).

I am trying to do this using JQuery and here's my attempt:

 $("vi").each(function(){ var temp = $(this).text(); temp = temp.split(':'); temp[0] = "<strong>" + temp[0].trim() + "</strong>"; temp[1] = "<em>" + temp[1].trim() + "</em>"; temp = temp.join(""); $(this).text(temp); }); 
 vi { color: red; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <html> <body> <vi>Dracula: bleh bleh bleh</vi> </body> </html> 

Any idea why this wouldn't work? When I try running it, it just outputs the text along with the tags I added as is, ie it displays "" instead of applying it, and so on.

You need .html() , not .text() , since you are inserting HTML into an element:

$("vi").each(function(){
   var temp = $(this).text();
   temp = temp.split(':');
   temp[0] = "<strong>" + temp[0].trim() + "</strong>";
   temp[1] = "<em>" + temp[1].trim() + "</em>";
   temp = temp.join("");
   $(this).html(temp);
});

Also, if I'm understanding the description of what you want, your CSS style should be:

vi strong {
  color: red;
}

Note: vi is not a valid HTML element - but you probably already knew that.

 $("vi").each(function(){ var temp = $(this).text(); temp = temp.split(':'); temp[0] = "<strong>" + temp[0].trim() + "</strong>"; temp[1] = "<em>" + temp[1].trim() + "</em>"; temp = temp.join(": "); $(this).html(temp); }); 
 vi strong { color: red; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <vi>Dracula: bleh bleh bleh</vi> 

Set html() to the element. Read http://api.jquery.com/html

 $("vi").each(function(){ var temp = $(this).text(); temp = temp.split(':'); temp[0] = "<strong>" + temp[0].trim() + "</strong>"; temp[1] = "<em>" + temp[1].trim() + "</em>"; temp = temp.join(": "); $(this).html(temp); }); 
 vi { color: red; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <html> <body> <vi>Dracula: bleh bleh bleh</vi> </body> </html> 

You need to use $.fn.html method. It is convenient to use it with a function parameter, it will run each loop internally for you:

 $("vi").html(function(_, text) { text = text.split(':'); return "<strong>" + text[0].trim() + "</strong> <em>" + text[1].trim() + "</em>"; }); 
 vi {color: red;} 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <vi>Dracula: bleh bleh bleh</vi> 

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM