Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I need to addclass or append class name same from content. Here is example.

<ul>
  <li>
    <a href="#">men</a>
    <ul>
      <li><a href="#">new arrival</a></li>
      <li><a href="#">about</a></li>
    </ul>
  </li>
  <li>
    <a href="#">top 2nd menu</a>
    <ul>
      <li><a href="#">go</a></li>
      <li><a href="#">hello menu</a></li>
    </ul>
  </li>
</ul>

Here is what I want as final result onload:

<ul>
  <li class="men">
    <a href="#">men</a>
    <ul>
      <li class="new-arrival"><a href="#">new arrival</a></li>
      <li class="about"><a href="#">about</a></li>
    </ul>
  </li>
  <li class="top-2nd-menu">
    <a href="#">top 2nd menu</a>
    <ul>
      <li class="go"><a href="#">go</a></li>
      <li class="hello-menu"><a href="#">hello menu</a></li>
    </ul>
  </li>
</ul>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
188 views
Welcome To Ask or Share your Answers For Others

1 Answer

you can do this with a little JQ .

A. first you need to find the text form each a that corresponds to each li.

to do that use the text() function ( info here )

B. then if you have more than one word as text you need to join the words with - using the replace() method (info here).

this is because if you don't join the words ( put "-" between them ), for example for text top 2nd menu then the li will have 3 separate classes instead of only one. so by using the replace() method you get the wanted result, respectively top-2nd-menu

C. and then add class to your li with attr("class","nav-" + addcl) ( info here )

this way you add whichever word you want before the text ( addcl ) you got from points A and B

$("li").each(function(){


var litext = $(this).children("a").text()
var addcl = litext.replace(/s/g, '-').toLowerCase()
$(this).attr('class', 'nav-' +  addcl);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
    <li><a href="#">men</a>
      <ul>
      <li><a href="#">new arrival</a></li>
      <li><a href="#">about</a></li>
      </ul>
    </li>
    <li><a href="#">top 2nd menu</a>
      <ul>
      <li><a href="#">go</a></li>
      <li><a href="#">hello menu</a></li>
      </ul>
    </li>
</ul>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...