Today I’m continued with the DOM chapter in the 📺 SuperSimpleDev JavaScript Tutorial on YouTube. Lets go!! 🔥👨💻🟨
My Code
If there are several buttons but I only want to edit some, I can use classes.
💡 Useful: the naming convention for these classes is ‘js-…’ if they are used for JavaScript
<body>
<button>This is button 1</button>
<button class="js-button">This is button 2</button>
<script>
console.log(document.querySelector('button').innerHTML);
document.querySelector('button').innerHTML = 'Changed 1';
const buttonElement = document.querySelector('.js-button'); // classes for js are usually named 'js-...'
console.log(buttonElement);
</script>
</body>
Now here is a button that can change back and forth with JavaScript
<body>
<p>YouTube Subscribe Button</p>
<button onclick="
const buttonElement = document.querySelector('.js-subscribe-button');
if (buttonElement.innerText === 'Subscribe') {
buttonElement.innerHTML = 'Subscribed'
} else {
buttonElement.innerHTML = 'Subscribe'
}
" class="js-subscribe-button">Subscribe</button>
</body>
But this is not very clean since HTML and JS is mixed up, so let’s separate that out with a function. (to my understanding this is still not separated as much as it should be, but perhaps that comes up later in the course)
<body>
<p>YouTube Subscribe Button</p>
<button onclick="
subscribe();
" class="js-subscribe-button">Subscribe</button>
<script>
function subscribe() {
const buttonElement = document.querySelector('.js-subscribe-button');
if (buttonElement.innerText === 'Subscribe') {
buttonElement.innerHTML = 'Subscribed'
} else {
buttonElement.innerHTML = 'Subscribe'
}
}
</script>
</body>
Alright that’s it again for today. Tomorrow I’ll upgrade the Rock Paper Scissors game from a few days ago with the newly learned code 😄