Adding Styling to Multiple Elements

The nice thing about not having an actual programmer’s job is that I can experiment and contribute coding at work without the pressure of immediate product. A recent enhancement I got to work on while editing content on a page: changing the style of several form options that did not reference a file.

function grayOptions(){
  const options = document.querySelectorAll('option[value=""]');
  options.forEach(option => option.classList.add('gray-out'))
}
document.addEventListener('DOMContentLoaded', grayOptions, false);

I was so proud of myself! Until Internet Explorer beat me down. Why, oh, why do only half of these things work in IE?!? I removed the fat arrow function, changed out ‘classList.add()’ with ‘className’, and changed up the forEach method a bit. All to accommodate IE’s partial or lack of support. Phew!

CSS-Tricks wrote a great article Loop Over querySelectorAll Matches to help me understand the forEach problem. My new solution that now works across all browsers:

function grayOut(){
        const options = document.querySelectorAll('option[value=""]'),
              optionsLen = options.length;
        let i;
        for(i = 0; i < optionsLen; ++i){
            options[i].className = 'gray-out';
            options[i].setAttribute('title','no file available');
        }
}
document.addEventListener('DOMContentLoaded', grayOut, false);

It’s these little coding wins that give me the encouragement I need to keep on digging deeper into the complex art of front-end development.

Advertisements

2 Replies to “Adding Styling to Multiple Elements”

  1. much as i love the way you try to maneuver through the quirks of browser compatibility…..Problem is that makes your code more verbose leading to more Coding mistakes, maintainability debts etc… You should consider making “jQuery your friend…”.

    Liked by 1 person

    1. Thanks for the tip! jQuery is very easy and useful. I’ve been on a journey to learn vanilla JavaScript, so that’s where this comes into play. In actuality, the site I worked on does use jQuery, and your advice is really the best plan, in this case. I do need to keep in mind the possibility of coding mistakes and maintainability debts. Those are big problems in bigger projects, and can be a hard lesson to learn.

      Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s