JavaScript and CSS

CSCI-UA.0480-008

Topics

  • selectors
  • querySelector
  • classList
  • best practices

Let's Practice Some Selectors


<h1>Some Elements:</h1>
<a>Link Zero</a>

<div id="container">
<a>Link One</a>
<h2>A List:</h2>
<ul>
	<li><a>Link Two</a></li>
	<li><a>Link Three</a></li>
</ul>
</div>

How Do You…

Change all of the headers so that their color is green?


h1, h2 { color:#0f0; }

Change all links so that when you hover over them, they change to twice the size of the root element's font size.


a:hover { font-size:2rem; }

Change "Link One" so that its background is yellow.


#container > a { background-color: #ff2; }

Change the color of all links nested under the div with id="container" to red.


#container a { color: #f00;}

Selector Summary

  • A E - Any E element that is a descendant of an A element (that is: a child, or a child of a child, etc.)
  • A > E - Any E element that is a child of an A element
  • E:first-child - Any E element that is the first child of its parent
  • B + E - Any E element that is the next sibling of a B element (that is: the next child of the same parent)

Selector Summary Continued

  • :hover - mouse hovers over (any element, not just links)
  • :link - non visited link
  • :visited - visited link

Using JavaScript with CSS Selectors

I've been holding out on you.

Yeah, document.getElementById is pretty good, but it's kind of a drag because you have to slap ids on everything.

You can use the following methods to select elements by their CSS selector!

  • document.querySelector('selector') returns a single matching element
  • document.querySelectorAll('selector') - returns a list of matching elements


Let's try these out with the selectors from the previous slide.

Revisiting ClassList

Let's take a quick look at the classList property again.

In addition to add and remove, classList also has a toggle method:


ele.classList.toggle('someClassName')
  • it will remove the class if it's present
  • it will add the class if it's not

On Style

Stylesheets can get unwieldy pretty quickly. Some ways to keep things readable an organized are:

  • use grouped /multiple selectors
  • one property value per line, indented
  • comments (/\* \*/) when appropriate
  • group like rules together or use some other organization scheme
  • use container elements if you need to hook into style exceptions
  • use a framework and/or use a css precompiler!


Some others in:

Some Best Practices

Besides the previous slide on organizing CSS, we also learned:

  • use relative sizing so that you only need to change your code in one place
  • modify classes instead of individual styles to separate application logic from presentation
  • use the appropriate positioning, box model and display property to layout your document