Changing Values & Attributes

Open the project folder

In our starter files, open the index.html page from this lessons folder:

04.Events-And-The-DOM > 02.Changing-values-and-attributes

Selecting elements

Now have our elements selected, how do we change them?

We will now cover how we can change the values of elements, and how to add and remove attributes using JavaScript. Over to the starter files, we have a simple header and image set up:

<body>
  <header>
    <h1 id="site-title">Meaty Burgers</h1>
    <nav>
      <ul class="nav-inline">
        <li class="nav-item">our burgers</li>
        <li class="nav-item">history</li>
      </ul>
    </nav>
  </header>
  <img src="burger.jpg" />
</body>

And we can change these elements using JavaScript. First, we can modify the text content of elements, here in the title, we can change it to be "No meat" burgers.

Add a span element around the text of "Meaty":

<h1 id="site-title"><span class="change-title">Meaty</span> Burgers</h1>

And we can now select just this section:

<script>
  const el = document.querySelector('.change-title');
</script>

To begin making changes to this element, like with most things in JavaScript, it all begins with a parent object, where we inherit things from:

console.log(typeof el);

Logging this to the console will return an object, an element object. And like other objects, this means we can also access methods and properties on this object to do things with it. There are many of these to choose from, but we can now uncover some common ones.

Modifying text

To begin, we can get the text contents of the element with innerText:

console.log(el.innerText);

Which selects the text of “Meaty” from between the tags. We can also use this to set new text:

const el = document.querySelector(".change-title");
el.innerText = "No Meat";
console.log(el);

Using markup

This will change the title, but what if we also wanted to add some markup too like this:

el.innerText = '<mark>No Meat</mark>';

This will display the tags in the browser as text, rather than format the text. For this use we need to change innerText to be innerHTML:

el.innerHTML = '<mark>No Meat</mark>';

For simple text content we will stick to innerText:

el.innerText = 'No Meat';

Selecting attributes

Along with the text content, we can also get attributes such as id, class, href, src, and set new ones too. For this, over to the console. We know the span we selected has a class, which we can grab like this:

el.getAttribute('class')
"change-title"

We also know we have no id on the span so this will return null:

el.getAttribute('id')
null

And we could use these in our code editor and store the values into a variable if needed.

Selecting the id of an element

We can also directly access an id property on the element:

const el = document.querySelector('.change-title');
el.innerText = 'No Meat';
// set new id:
el.id = 'new';
// see in console
console.log(el);

If an id is already present in the HTML code, it will override the initial value.

This element also has some methods to work with attributes. We have getAttribute as discovered above, along with setAttribute and removeAttribute:

Set new attributes

We can set any attribute such as a class. The CSS section of the head has a .green class already set in the head section:

.green {
  color: rgb(40, 141, 40);
}

To add this to an element, we can use setAttribute:

const el = document.querySelector('.change-title');
el.innerText = 'No Meat';
el.id = 'new';
// To set attributes, we need to pass in 2 values. The name of the attribute, and the value:
el.setAttribute('class', 'green');
console.log(el);

The green title should now show, and the class is visible in the console:

<span class="green" id="new">No Meat</span>

Do you notice anything about the class attribute? The original class name of change-title is now missing. This happens because setAttribute only adds a single value and will override any existing values.

To add an extra class, we need to do it another way and will look at this in just a moment.

Removing attributes

We can also remove any attribute with the removeAttribute method:

const el = document.querySelector('.change-title');
el.innerText = 'No Meat';
el.id = 'new';
el.setAttribute('class', 'green');
el.removeAttribute('id');
console.log(el);

This will remove the id we set above.

Dynamic image src attribute

Working with attributes like this is useful for things like updating images. Out index page has an image already set, remove the image src from the html, leaving this:

<img />

We can dynamically add this back in using our script:

const image = document.querySelector('img');
image.setAttribute('src', 'burger.jpg');
image.setAttribute('alt', 'burger image');

A use case for this could be to make games show up random images and add or remove classes to change the look of things. Such as at the end of a game we may want to add a class to show or hide some sections, we could set green text for a win, or red text for a defeat.

Retrieving multiple classes

Multiple class names can also be retrieved in multiple ways. We can first add multiple classes in our title to see this:

<h1 id="site-title"><span class="change-title blue red">Meaty</span> Burgers</h1>

And comment out the green class addition below so it does not override these:

const el = document.querySelector('.change-title');
el.innerText = 'No Meat';
el.id = 'new';
// el.setAttribute('class', 'green');
el.removeAttribute('id');
console.log(el);

We can now retrieve these classes in different ways. If we want a string containing all the class values, we have the className property:

Try this out in the console:

el.className
'change-title blue red'

Notice the returned value is a string. And using the classList property, we can get back an array-like collection of classes called a DOMTokenList:

el.classList
DOMTokenList(3) ["change-title", "blue", "red", value: "change-title blue red"]

As with arrays, a DOMTokenList is indexed from 0, meaning we can select individual values by their index number:

el.classList[1]
'blue'

If we need these values, they can also be stored in variables in our editor.

Adding/removing multiple classes

But back to the issue of adding multiple classes. Using classList we also have access to the add and remove methods:

el.classList.add('green', 'cyan');
console.log(el);

This way can add multiple classes to the existing ones. And also remove too:

el.classList.add('green', 'cyan');
el.classList.remove('red');
console.log(el);

If we wanted to go even further, we could set up a variable containing our class names:

const classes = ['yellow', 'pink'];
// spread these array values in:
el.classList.add(...classes);

Recap

  • We can select an element, and set the text value with innerText, we have innerHTML to add html content inside of our element. And we can set or update an existing id attribute with the id property.
  • We also have full control over our attributes too, we can get any existing attributes such as a class or src, we can set new ones, and remove any attributes.
  • And last of all we looked at classes and the different ways we can add, update, and remove them.