Skip to content Skip to sidebar Skip to footer

How To Access Li Elements Within Ul Tag

I want to know how to access each li within the ul? I am not sure exactly what the name of the ul is. Here is the code:
    Copy

    If you're not sure that the ul will have the selectBox-options class, then delete the .selectBox-options part - but remember that it will get you every li on the page then.

    If you're using jQuery, then this is a bit more compatible, and does basically the same thing:

    var li =  $("ul.selectBox-options li");
    

Solution 2:

If you accept jQuery, like you mentioned:

$( "li" ).each(function( index ) {
    console.log( index + ": " + $(this).text() );
});

As the jQuery documentation declares.

I'm not sure how to do it with raw javascript though :)


Solution 3:

in CSS:

li { color:black; }

with ul:

ul li { }

or with class:

ul li.ommitted { }

or with ul&li class

ul.selectBox-options li.ommitted { }

ps. Don't forget the end tag

</li>

Solution 4:

<html>
  <head>

    <style type='text/css'>
      .omitted {
        color:                  rgb(0, 0, 0);
        background:             transparent;
      }

      .selected {
        color:                  rgb(255, 255, 255);
        background:             rgb(0, 0, 0);
      }
    </style>

    <script type='text/javascript'>
      function matchSelected(foo) {
        var selectBox =         document.getElementById('selectBox');
        var items =             selectBox.getElementsByTagName('LI');

        for(i=0; i<items.length; i++) {
          items[i].className =  items[i].innerHTML == foo ? 'selected' : 'ommitted';
        }
      }
    </script>

  </head>


  <body>


    <ul id='selectBox' class='selectBox-options exp-pdp-size-dropdown exp-pdp-dropdown'>
      <li class='omitted'>1</li>
      <li class='omitted'>3</li>
      <li class='omitted'>8</li>
      <li class='omitted'>10</li>
      <li class='omitted'>14</li>
    </ul>


    <select onChange='matchSelected(this.value);'>
      <option value='1'>One</option>
      <option value='3'>Three</option>
      <option value='8'>Eight</option>
      <option value='10'>Ten</option>
      <option value='14'>Fourteen</option>
    </select>


  </body>
</html>

Solution 5:

You want like this? DEMO http://jsfiddle.net/yeyene/ZjHay/

$(document).ready(function(){
    $('select').on('change',function(){
        alert($('.selectBox-options li').eq($(this).val()-1).text());
    });
});

Post a Comment for "How To Access Li Elements Within Ul Tag"