css Audio - Active file-generic CSS - Active Generic - Active HTML - Active JS - Active SVG - Active Text - Active file-generic Video - Active header Love html icon-new-collection icon-person icon-team numbered-list123 pop-out spinner split-screen star tv
CodePen probably won't work great in this browser. We generally only support the major desktop browsers like Chrome, Firefox, Safari, and Edge. Use this one at your own risk! If you're looking to test things, try looking at Pens/Projects in Debug View.
user profile image

A comparison of how to select elements using CSS and JavaScript


  1. #id selectors are considered evil in CSS by most authors, because it's next to impossible to overwrite the rules with class-selectors.

    i like using the attribute selector [id=elementid] { ... } instead -- because it offers the same specificity as .class selectors

  2. @grilly You'd think #demo and [id=demo] would be equally strong, but that's not actually true! In fact #demo is a stronger selector than [id=demo], even if [id=demo] comes after it in CSS.

    .demo and [class=demo] are of equal strength though, so whichever comes last will override previous declarations of the same strength.

    Test it out for yourself: http://codepen.io/tomhodgins/pen/eJqwpj

    You can't assume anything with CSS, you have to test every behaviour you want to use. I will be teaching HTML by explaining about attributes and I'll show my students [id=demo] long before I teach them #demo because it's the same way you can select any attribute, but you should be aware that # is special, why it's special, and exactly what it does for you so you know the right time to use it :)

  3. Yep, test modify, test again, and then some. @grilly, I see so many evil usages of CSS and JS, using ID's seems rather trivial. And a pro coder doesn't have to overwrite classes. I don't wonna start a discussion though, so many designers so many opinions.

    Nice and clear explanation, Tommy! Thanks for sharing...

  4. Great resource. It's always good to show the comparisons. I think it helps people bridge the gaps when they only know one side.

  5. Why didn't you use querySelectorAll('span')?

  6. @alvarezjacob while querySelectorAll('span') will select all tags equivalent to the CSS selector span, the example in my demo demonstrates the CSS and JS way of targeting an element by its tag name.

    You could also use querySelector() in place of getElementById() every time, however you can querySelector() for a lot more than just id's so it's not a good example of that.

    Where I think querySelectorAll() shines is when searching for really complex CSS selectors, like iframe[src*=youtube] which couldn't be done with a simple getElementsByTagName() :)

  7. Yes my big reason for jQuery ;)

Leave a Comment Markdown supported. Click @usernames to add to comment.

You must be logged in to comment.