Where does class 'message" come from?

I can see a class named ‘message box’ below in a p element, but I can’t find a class named 'message", so where it comes from? Is it because the p named ‘message box’ so the text in it name ‘message’?

  **Your code so far**

<script>
document.addEventListener('DOMContentLoaded', function(){
  document.getElementById('getMessage').onclick = function(){
    // Add your code below this line
    document.getElementsByClassName('message')[0].textContent="Here is the message";


    // Add your code above this line
  }
});
</script>

<style>
body {
  text-align: center;
  font-family: "Helvetica", sans-serif;
}
h1 {
  font-size: 2em;
  font-weight: bold;
}
.box {
  border-radius: 5px;
  background-color: #eee;
  padding: 20px 5px;
}
button {
  color: white;
  background-color: #4791d0;
  border-radius: 5px;
  border: 1px solid #4791d0;
  padding: 5px 10px 8px 10px;
}
button:hover {
  background-color: #0F5897;
  border: 1px solid #0F5897;
}
</style>

<h1>Cat Photo Finder</h1>
<p class="message box">
The message will go here
</p>
<p>
<button id="getMessage">
  Get Message
</button>
</p>
  **Your browser information:**

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36

Challenge: Change Text with click Events

Link to the challenge:

In HTML, a class is just a label that you can give to 1 or more elements. This class was “created” when someone added that string to the class attribute of that p. Poof, it exists. What you choose to do with it is up to you. You could use it to target elements with some CSS. They’re not doing that here. You’re using it to target elements with that class for DOM manipulation.

1 Like

So we don’t need to create a ‘message’ class like the way we create a const or var?

We actually do two different things, as there are two different classes. The box class is being used in the CSS to define a presentational style. The message class is being used as a Javascript “hook,” allowing us to connect to the DOM.

We don’t need to define a CSS style rule for every class, only the ones we want to style in a particular way.

It can often be convenient to create more classes than we strictly need, as we can then use those to gather different groupings of related elements (all .messageelements, all .error.message elements, or all li.box to subset a particular collection of box elements).

We can apply CSS to these as we need, but we can also connect to a class, out any other CSS style selector, to hook into the DOM for interactive manipulation.

2 Likes