Supposing I have a table that has been dynamically generated with one of the columns having a unique span id:
<tr><td><span id="123"></span></td></tr>
<tr><td><span id="124"></span></td></tr>
<tr><td><span id="125"></span></td></tr>
<tr><td><span id="126"></span></td></tr>
What is the best way to iterate through the spans with a javascript function so that the span id can be passed as a value that the function can then use?
Assign a same class to each of the span items and then make use of getElementsByClassName and iterate through the array.
var targetElements = document.getElementsByClassName('target');
Update (with jQuery)
You may be able to use iterate through this using the following code as well.
jQuery('table td > span').each(function() {
var id = jQuery(this).attr('id');
// Your logic
});
Use the jQuery each
function to iterate over your span
s and do something with their id
property:
$('#table-id span').each(handleElement) function handleElement () { var id = this.id // Do something with `id` console.log(id) }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table id="table-id"> <tr><td><span id="123"></span></td></tr> <tr><td><span id="124"></span></td></tr> <tr><td><span id="125"></span></td></tr> <tr><td><span id="126"></span></td></tr> </table>
Use the jquery loop construct to loop through the table data.
$("tr td").each(function() { var foo = $(this).find("span").attr('id'); });
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.