I'm taking a basics class on JavaScript and I have not been able to follow along since minute one. This language makes no sense to me. I get HTML and CSS, but JS is nonsense to me.
I'm trying to practice and learn by doing, but I can't even get past the first line of code. Here's what I have:
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Buttons</title>
<link rel="stylesheet" href="css/style.css">
<script src = "js/jScript.js"></script>
</head>
<body>
<p><button type="button" class="btn" ></button></p>
<p><button type="button" class="btn" ></button></p>
<p><button type="button" class="btn" ></button></p>
</body>
</html>
/* CSS SHEET */
@charset "UTF-8";
.btn{
width: 10px;
height: 40px;
background: gray;
}
// JAVASCRIPT //
function btnStyle(){
document.getElementsByClassName("btn").style.width="120px";
}
All I am trying to do is change all the buttons with class "btn" to have a width of 120px. By my limited understanding, this should work. I don't want an alternative way to accomplish this. I want an explanation of WHY this doesn't work.
As has been noted, you can't access a specific instance of an element when working with a collection of elements unless you dig into the collection. It's like having a classic car collection and saying "change the color to blue" in reference to the collection when you really meant to change just one car's color.
Next, avoid
.getElementsByClassName(). It's a 25+ year old way of scanning the DOM for a collection of matching elements, but it returns what's called a "live node list" and can hurt performance greatly. Frankly, any course you are taking to learn this should not be teaching this API and you should let your instructor know that they are teaching out of date stuff.See the comments below: