Is it possible to iterate over a Bootstrap list?

I have a list Twitter Bootstrap

with a variable number of items (actually there are two lists with drag and drop items done with Sortable.js ).

At some point, I want to iterate over these list items to get the data attribute from each list entry. This is what my list looks like in HTML:

       <div class="panel-body">
            <ul id="main_list" class="list-group">
                <li id="opt1" href="#" class="list-group-item" data_value="1">Opt 1</li>
                <li id="opt2" href="#" class="list-group-item" data_value="2">Opt 2</li>
                <li id="opt3" href="#" class="list-group-item" data_value="3">Opt 3</li>
            </ul>
        </div>

      

Can this be achieved or am I being too objectively oriented? If not, how do I revisit this task?

+3


source to share


2 answers


You can provide your specific information like

<li id="opt3" href="#" class="list-group-item" data-value="3">Opt 3</li>

      

and it's easy to get this with jquery:

$("#opt3").data("value")

      

But the semantic way to do it is with "-" instead of "_".




To view the list again, you can:

$("#main_list li").each(function(){
  var itemValue = $(this).data('id');
  var itemName = $(this).data('name');
  alert(itemValue+" - " +itemName);
});
      

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
   <div class="panel-body">
            <ul id="main_list" class="list-group">
                <li id="opt1" href="#" class="list-group-item" data-name="customname1" data-id="1">Opt 1</li>
                <li id="opt2" href="#" class="list-group-item" data-name="customname2" data-id="2">Opt 2</li>
            </ul>
        </div>
      

Run code


+3


source


Thiago's answer is completely valid and if jQuery is already in use this should be the accepted answer. But there is a solution for this in simple js:

var elements = document.getElementById('main_list').children,
    maxElements = elements.length,
    counter = 0,
    tmpAttribute;

for (; counter < maxElements; counter++) {
    tmpAttribute = elements[counter].getAttribute('data_value');
    // whatever you need to do with tmpAttribute
}

      



You can wrap this in a function and call it by pushing eg. Here's a demo to see it in action: http://jsfiddle.net/Lzcbzq7x/1/

+2


source







All Articles