JSFiddle - React, Tailwind, and code Playground
HTML
<div class="container">
<div class"inline">
<p id="text">Image</p>
<p id="clickedText"></p>
<img...
CSS
.container {
display: flex;
}
.inline {
display: inline-grid;
}
img {
width: 150px;
height: 100px;
cursor: pointer;
}
p {
cursor: pointer;
}
button {
width: 80px;
height: 30px;
font-size: 12px;
margin-left: 20px;
border: none;
border-radius: 10px;
background: red;
color: white;
}
.grid {
margin-left: 20px;
}
li {
cursor: pointer;
}
ol li {
font-size: 15px;
}
.description {
font-size: 12px;
margin-top: 40px;
}
.recipe {
margin-left: 20px;
cursor: pointer;
}
JavaScript
// 1. querySelector
// You get img element by querySelector from HTML - it's one element and not array
// You call function addEventListener on that element
// After clicking the image, an alert is displayed
const image = document.querySelector("img");
image.addEventListener("click", function() {
alert("You clicked image!");
});
// 2. getElementsByTagName
// You get all li by getElementsByTagName from HTML
// You go through each element
// You take every single el
// You call function addEventListener on that element
// After clicking the element, in console a message is displayed that you have clicked on the element
const elementsByTagName = document.getElementsByTagName('li');
for (let i = 0; i < elementsByTagName.length; i++) {
const el = elementsByTagName[i];
el.addEventListener("click", () => {
console.log("You clicked elements by tag name! - " + el.textContent)
});
}
// 3. getElementsByClassName
// You get all the elements in class 'recipe' by getElementsByTagName from HTML
// You go through each element with this specific class name
// You take every single element
// You call function addEventListener on that element
// After clicking the element, in the console a message is displayed that you have clicked on the element with class 'recipe'
const elementsByClassName = document.getElementsByClassName('recipe');
for (let i = 0; i < elementsByClassName.length; i++) {
const el = elementsByClassName[i];
el.addEventListener("click", () => {
console.log("You clicked elements by class name! - " + el.textContent)
});
}
// 4. getElementById
// You get p element by getElementById from HTML with a unique id 'text'
// You call functions addEventListener on that element
// After clicking this element, it will display different text with different css properties
const text = document.getElementById('text');
// You get p element by getElementById from HTML with a unique id 'clickedText'
const clikText =...