Style Page Content

In this section, we'll be looking at controlling page and element styling using the following properties and methods:

  • .style.<prop>
  • .cssText()
  • .setAttribute()
  • .className
  • .classList

QUESTION 1 OF 6

Before we begin, put these in the correct order of CSS specificity. Put the least-specific option at the top and the most-specific option at the bottom.

LEVEL OF SPECIFICITY

rules in a tag's style attribute

rules in a<style>tag

rules in a stylesheet

CSS RULE

Least specific

More specific

Most specific

SUBMIT: rules in a stylesheet / rules in a <style> tag / rules in a tag's style attribute

CSS Specificity

To be successful in this section, it will help to have an understanding of how CSS Specificity works. According to the MDN, "specificity" is:

the means by which browsers decide which CSS property values are the most relevant to an element and, therefore, will be applied.

Basically, the closer the style rule is to an element, the more specific it is. For example, a rule in a style attribute on an element will override a style rule for that element in a CSS stylesheet. There is also the specificity of thetype_of selector being used. An_ID_is more specific than a_class.

If you'd like to learn more about CSS Specificity, check out the following links:

Modifying an Element's Style Attribute

Let's jump back to your knowledge of CSS. When trying to style an element, the most-specific rules that you can write for an element are written in that element'sstyleattribute. Lucky for us, we can access access an element'sstyleattribute using the.styleproperty!

const mainHeading = document.querySelector('h1');

mainHeading.style.color = 'red';

Now, I want to point out that when using the.styleproperty, you can only modify_one_CSS style at a time. That's why the previous code has.style.color = 'red'and not just.style = 'red'.

Check out the documentation page for more information:style docs

Reflect

Why do you think it has to befontSize? Why wouldfont-sizenot work?

SUBMIT

Reflect

Write the JavaScript code to set the width of element to 50%;

SUBMIT

Adding Multiple Styles At Once

We've seen how the.style.<property>syntax will let us change_just one_piece of styling for an element. So if we wanted to set an element's color, background color, and font size, we'd have to use three separate lines of code:

const mainHeading = document.querySelector('h1');

mainHeading.style.color = 'blue';
mainHeading.style.backgroundColor = 'orange';
mainHeading.style.fontSize = '3.5em';

...and that's just for setting_three_styles. Imagine if we needed 15 or 20 different styles! So the.style.propertysyntax is perfect for setting one style at a time, but it's not great for controlling multiple styles.

Fortunately, we can use the.style.cssTextproperty to set multiple CSS styles at once!

const mainHeading = document.querySelector('h1');

mainHeading.style.cssText = 'color: blue; background-color: orange; font-size: 3.5em';

Notice that when using the.style.cssTextproperty, you write the CSS styles just as you would in a stylesheet; so you writefont-sizerather thanfontSize. This is different than using the individual.style.<property>way.

QUESTION 4 OF 6

<p id="quizzing-quizzes" style="color: orange;">Howdy</p>

For the element above, which of the following styles will be applied after running this code?

document.querySelector('#quizzing-quizzes').style.cssText = 'width: 30px; textDecoration: underline;';
  • color

  • text-decoration

  • width

  • none

SUBMIT: C ( Only the width styling will be in the element's style attribute. The.style.cssText will overwrite anything that's already in the .style attribute (which removes the color styling). The textDecoration rule is misspelled and should be text-decoration , so it gets dropped.)

Setting An Element's Attributes

Another way to set styles for an element is to bypass the.style.<property>and.style.cssTextproperties altogether and use the.setAttribute()method:

const mainHeading = document.querySelector('h1');

mainHeading.setAttribute('style', 'color: blue; background-color: orange; font-size: 3.5em;');

Check out the documentation page for more information:style docs

.setAttribute()Is Not Just For Styling

ThesetAttribute()method is not_just_for styling page elements. You can use this method to set_any_attribute for an element. If you want to give an element an ID, you can do that!:

const mainHeading = document.querySelector('h1');

// add an ID to the heading's sibling element
mainHeading.nextElementSibling.setAttribute('id', 'heading-sibling');

// use the newly added ID to access that element
document.querySelector('#heading-sibling').style.backgroundColor = 'red';

The last two lines could've been combined into one to bypass setting an ID and just styling the elment directly:

mainHeading.nextElementSibling.style.backgroundColor = 'red';

...but this was just to demonstrate that it's possible to set an attribute with JavaScript that affects the DOM which then can be used immediately

Accessing an Element's Classes

The first element property we'll look at is the.classNameproperty. This property returns a string of all of the element's classes. If an element has the following HTML:

<h1 id="main-heading" class="ank-student jpk-modal">Learn Web Development at Udacity</h1>

We could use.classNameto access the list of classes:

const mainHeading = document.querySelector('#main-heading');

// store the list of classes in a variable
const listOfClasses = mainHeading.className;

// logs out the string "ank-student jpk-modal"
console.log(listOfClasses);

The.classNameproperty returns a space-separated string of the classes. This isn't the most ideal format, unfortunately. We can, however, convert this space-separated string into an array using the JavaScript string method,.split():

const arrayOfClasses = listOfClasses.split(' ');

// logs out the array of strings ["ank-student", "jpk-modal"]
console.log(arrayOfClasses);

Now that we have an_array_of classes, we can do any data-intensive calculations:

  • use a for loop to loop through the list of class names
  • use .push() to add an item to the list
  • use .pop() to remove an item from the list

.classNameis a property, so we can set its value just by assigning a string to the property:

mainHeading.className = "im-the-new-class";

The above code_erases_any classes that were originally in the element'sclassattribute and replaces it with the single classim-the-new-class.

Since.classNamereturns a string, it makes it hard to add or remove individual classes. As I mentioned earlier, we can convert the string to an array and then use different Array Methods to search for a class remove it from the list, and then update the.classNamewith the remaining classes. However, we don't want to do all of that work! Let's use the newer.classListproperty.

The.classListProperty

The.classListproperty is newer than the.classNameproperty, but is much nicer, check it out:

<h1 id="main-heading" class="ank-student jpk-modal">Learn Web Development at Udacity</h1>
const mainHeading = document.querySelector('#main-heading');

// store the list of classes in a variable
const listOfClasses = mainHeading.classList;

// logs out ["ank-student", "jpk-modal"]
console.log(listOfClasses);

Check out the documentation page on MDN:classList docs

QUESTION 5 OF 6

Review theclassList property's documentation. What data structure does the.classListproperty return?

  • an array

  • a NodeList

  • a DOMTokenList

  • an ElementList

SUBMIT: C

The.classListproperty has a number of properties of its own. Some of the most popularly used ones are:

  • .add() - to add a class to the list
  • .remove() - to remove a class from the list
  • .toggle() - to add the class if it doesn't exists or remove it from the list if it does already exist
  • .contains() - returns returns a boolean based on if the class exists in the list or not

Let's take a look!

QUESTION 6 OF 6

What happens if you try to toggle a nonexistent class? For example, if you had this HTML:

<h1 id="main-heading" class="ank-student jpk-modal">Learn Web Development at Udacity</h1>

...what would happen after running the following JavaScript:

const mainHeading = document.querySelector('#main-heading');

mainHeading.classList.toggle('richard');
  • therichardclass is added to the list of classes

  • therichardclass is not added to the list; the existing list of classes remains the same

  • therichardclass replaces the other classes

  • an error happens

SUBMIT: A (Toggling a non-existent class will add the new class to the list of classes.)

Style Page Content Recap

We learned a ton of content in this section! We looked at:

  • modifying individual styles with .style.<prop>
  • updating multiple styles at once with .style.cssText
  • getting/setting a list of classes with .className
  • getting/setting/toggling CSS classes with .classList

My recommendation to you is that, out of the list of techniques you learned in this section, to use the.classListproperty more than any other..classListis by far the most helpful property of the bunch, and it helps to keep your CSS styling out of your JavaScript code.

Further Research

results matching ""

    No results matching ""