<div class="box"></div>
<div class="box"></div>
<div data-color="blue" class="box"></div>
html, body {
height: 100%;
}
body {
display: grid;
justify-content: center;
align-content: center;
}
.box{
display: grid;
justify-content: center;
align-content: center;
width: 250px;
height: 100px;
margin: 10px;
color: #fff;
font-family: sans-serif;
font-weight: bold;
}
.red {
background-color: red;
}
.blue {
background-color: blue;
}
/* The CSS Selector .box will match more than one element, but only the FIRST one is retrieved */
const red = document.querySelector('.box')
red.classList.add('red')
red.textContent = 'Red'
/* Tags and pseudo-classes can be used in querySelector */
const green = document.querySelector('div:nth-child(2)')
green.style.background = 'green'
green.textContent = 'Green'
/* Attributes can also be used in querySelector */
const blue = document.querySelector('[data-color]')
blue.classList.add(blue.dataset.color)
blue.textContent = 'Blue'
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.