Rawi Rai Rawi Rai - 3 months ago 16
jQuery Question

how to append class on li and ul using same content?

Hi need to addclass or append class name same from content. here is example. jQuery.



<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>




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 the final result add as a class to your li with attr("class","nav-" + addcl) function ( info here )

this way you add whichever word you want before the text ( 'addcl` ) you got from point 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>

Comments