I have a Twitter Bootstrap
list with a variable number of elements (in fact there are two lists with draggable and droppable elements done with Sortable.js ).
At some point, I want to iterate those lists elements in order to get a data atribute from each list entry. This is how my list looks like at 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>
Is this even possible to achieve, or am I thinking too object oriented? If not, how should I rethink this task?
You can put your specific information like
<li id="opt3" href="#" class="list-group-item" data-value="3">Opt 3</li>
and get that easily with jquery:
$("#opt3").data("value")
But the semantic way to do that is with "-" instead of "_".
To iterate your list, you can do:
$("#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>
Thiago's answer is totally valid, and if jQuery is already used then it should be the accepted answer. But for the sake of it here is a solution in plain 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 could wrap that in a function and call it on click for example. Here is a demo to see it in action: http://jsfiddle.net/Lzcbzq7x/1/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.