-->

Wrap different style to specific text between
  • 2019-02-19 11:49发布

    问题:

    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.

    Thanks in advance.

    回答1:

    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>



    回答2:

    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>



    标签: jquery css wrap