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

    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.

    标签: jquery css wrap
    2条回答
    姐就是有狂的资本
    2楼-- · 2019-02-19 12:08

    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>

    查看更多
    Root(大扎)
    3楼-- · 2019-02-19 12:16

    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>

    查看更多
    登录 后发表回答