dbj
dbj

Reputation: 125

Wrap different style to specific text between <li></li> before textual colon ":"?

Before I lose myself in words trying to explain what I mean, here's an example of what I'd like to achieve.

How it is now:

<ul>
    <li>My name: Sietse</li>
    <li>Country: The Netherlands</li>
</ul>

How I'd like it to be:

<ul>
    <li><strong>My name:</strong> Sietse</li>
    <li><strong>Country:</strong> The Netherlands</li>
</ul>

There is a lot of existing content on my website that is marked up like the first example, but is there a way to dynamically select and style the text until the (possibly including) the colon in the LI, as displayed in the second example?

Please note that I'm an absolute beginner in jQuery or any Javascript for that matter.

Upvotes: 2

Views: 204

Answers (2)

Subodh Ghulaxe
Subodh Ghulaxe

Reputation: 18661

Try following

$(function() {
  $("ul li").each(function() {
   if ($(this).text().indexOf(':') > -1) {
       $(this).html('<strong>' + $(this).html().split(':').join(':</strong>')); 
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul>
  <li>My name: Sietse</li>
  <li>Country: The Netherlands</li>
</ul>

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388406

You can use .html() and string replace() like

$('ul li').html(function (i, html) {
    return html.replace(/(.*?:)/, '<strong>$1</strong>')
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul>
    <li>My name: Sietse</li>
    <li>Country: The Netherlands</li>
</ul>

Upvotes: 4

Related Questions