Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

select all elements of class and iterate over each even object (nth child (even) replacement)

I'm displaying the alphabet with each letter having the same background (width 31px ). I need half of the letters to have a width of 30px. This is handled by:

div.alpha:nth-child(even) {width: 30px;}

However, this does not work in ie because of the pseudo compatibility issues.

I'm looking for a pure javascript alternative that works with ie IN quirks mode.

I tried:

function letterwidth () {
    var a = document.querySelectorAll ('div.alphabet');
    for (var i = 0, b = a.length; i < b; i++){
        if (i % 2 == 0) {
            a[i].style.width = '30px';
        }
    }
}

but I get an error:

SCRIPT438: Object doesn't support property or method 'querySelectorAll'

like image 829
Jamie Kudla Avatar asked Nov 29 '25 21:11

Jamie Kudla


1 Answers

If querySelector isn't supported by the browser, you'll need to use regular DOM traversal methods :

var el  = [],
    div = document.getElementsByTagName('div');

for (var i=0; i<div.length; i++) {
    if (div[i].className.indexOf('alphabet') != -1) 
        el.push(div[i]);
}

for (var i=0; i<el.length; i++){
    if (i % 2 == 0)
         el[i].style.width = '30px';
}

FIDDLE

like image 188
adeneo Avatar answered Dec 02 '25 11:12

adeneo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!