bswinnerton
bswinnerton

Reputation: 4721

Iterate through spans using javascript

Using only Javascript, how can I iterate through every span id = "expiredDate"? I would think that this would be quite easy with a for each loop, but it doesn't appear to exist in javascript. My below code only works for the first element.

<script type="text/javascript">
window.onload = function() {
    var definedDate = window.document.getElementById('expiredDate').innerHTML.split("-");
    var expiredDate = new Date(definedDate[0], definedDate[1] - 1, definedDate[2]);
    var graceDate = new Date(definedDate[0], definedDate[1] - 1, definedDate[2] - 30);
    var currentDate = new Date();

    if(currentDate > expiredDate) {document.getElementById('expiredDate').style.color = '#cc6666';}
    else if(currentDate < expiredDate && currentDate > graceDate) {document.getElementById('expiredDate').style.color = '#f0c674';}
    else {document.getElementById('expiredDate').style.color = '#b5bd68';}
}
</script>
<span id="expiredDate">2013-01-01</span>
<span id="expiredDate">2014-01-01</span>
<span id="expiredDate">2015-01-01</span>

Upvotes: 0

Views: 6806

Answers (3)

Paul S.
Paul S.

Reputation: 66334

Two methods not said yet; for both you should be using the form

<span class="expiredDate">...</span>

1. .querySelectorAll method:

var result = document.querySelectorAll('span.expiredDate'); // NodeList

2. .getElementsByClassName combined with Array.prototype.filter

var result = Array.prototype.filter.call(
                 document.getElementsByClassName('expiredDate'),
                 function (elm) { return elm.tagName === 'SPAN'; }
             ); // Array

Method 1 is faster, but because you're already iterating through them with method 2 you could save yourself a loop later by putting your desired actions inside the filter's function, therefore making it faster overall.

Upvotes: 2

Jason
Jason

Reputation: 2364

Switch your IDs to classes and try the following

var spans = document.getElementsByTagName('span');
var l = spans.length;
for (var i=0;i<l;i++) {
    var spanClass = spans[i].getAttribute("class"); 
    if ( spanClass === "expiredDate" ) { 
        /*do stuff to current spans[i] here*/
    }
}

Upvotes: 5

ryan
ryan

Reputation: 6655

Depends on which browser versions you are targeting. See caniuse's document.getElementsByClassName. Depending on your scope you could also use document.getElementsByTagName and iterate. Or use XPath or jQuery.

Upvotes: 0

Related Questions