5

Ok so I have this drop down and I want to bold the first word in the main level of the nav..See which ones in my code below with comments.

To make it clear I would like the words Our, Lorem, and Another to be wrapped in a strong tag or a span tag since they are the first words in the main level of the navigation. How can I accomplish this with jQuery?

<ul class="clearfix" id="topnav">
  <li class="mainNavFirst"><a href="/">Our Home</a></li> <!-- bold this 'our' -->
  <li class="mainNavMiddle"><a href="#">Lorem Ipsum</a><!-- bold this 'Lorem' -->
    <div>
      <ul>
        <li class="sectionTitle">
          <h2><a href="#">Ipsum Lorem</a></h2>
        </li>
        <li><a href="#">Just a random link</a></li>
        <li><a href="#">Just a random link</a></li>
      </ul>
      <ul>
        <li class="sectionTitle">
          <h2><a href="#">Ipsum Lorem</a></h2>
        </li>
      </ul>
    </div>
  </li>
  <li class="mainNavLast"><a href="#">Another Link</a></li><!-- bold this 'Another' -->
</ul>
breezy
  • 1,910
  • 1
  • 18
  • 35

4 Answers4

4
$('#topnav > li > a').html(function(i,html){
    return html.replace(/^\s*([^\s]+)(\s|$)/, '<span>$1 </span>');
});

http://jsfiddle.net/LKXKs/3/


EDIT: Fixed it so it will still work if there's only one word in the <a>, or if there are leading spaces.

user113716
  • 318,772
  • 63
  • 451
  • 440
2
    $(function(){
      $('#topnav > li > a').each(function(item, index){
            var firstWord = $(this).text().split(" ")[0];
            var newText = $(this).text().replace(firstWord, "<span>"+firstWord +"</span>");
            $(this).html(newText);
      });
    });

Then use CSS style:

#topnav > li > a span { font-weight: 800; }

Fiddle: http://jsfiddle.net/zbfcS/

Mutt
  • 937
  • 6
  • 9
1

Here is a good method, based on @jensgram's answer at First Word in String with jquery:

<script>
    boldFirstWord($(".clearfix .mainNavFirst > a"));
    boldFirstWord($(".clearfix .mainNavMiddle > a"));
    boldFirstWord($(".clearfix .mainNavLast > a"));

    function boldFirstWord(element) {
        element.html( element.html().replace(/^(\w+)/, '<strong>$1</strong>'));
    }
</script>
Community
  • 1
  • 1
George Cummins
  • 28,485
  • 8
  • 71
  • 90
0

Are you dynamically loading the nav or will it change frequently? If not, you probably do not need any extra scripting added to your page re changing the first word with js. Just add the strong tags to the appropriate word.

Jason Gennaro
  • 34,535
  • 8
  • 65
  • 86