Using CSS

Objectives

  • Explain basic CSS selectors
  • Access element style information using JavaScript
  • Set element style information using JavaScript
  • Discuss using jQuery to select elements

Resources

A few common CSS selectors (to get started)

  • *: selects all elements in document
  • tagname: selects elements with the specified HTML tag name
  • tagname1, tagname2: selects elements with either specified HTML tag name
  • tagname1 tagname2: selects elements with tagname2 which are descendants of an element with tagname1
  • .className: selects elements with the specified class name
  • #id: selects the element with the specified id
  • tagname.className: selects elements with the specified tag name and class name

Searching for elements based on CSS selectors

  • document.querySelector(cssSelector): returns the first element in a depth first tree traversal that matches the specified CSS3 selector
  • element.querySelector(cssSelector): returns the first element in a depth first subtree traversal starting with element that matches the specified CSS3 selector
  • document.querySelectorAll(cssSelector): returns a NodeList of all elements within the tree that match the specified CSS3 selector
  • element.querySelectorAll(cssSelector): returns a NodeList of all elements descended from element that match the specified CSS3 selector
  • jQuery uses the $() function which serves many purposes and returns a jQuery object which is a collection of the elements found. jQuery then provides a multitude of methods that can act upon the elements of that collection.

CSS specificity

See the following resources for details on CSS specificity.