0

I'm learning DOM manipulation as a beginner and have selected the tag in variable h. My online instructor is able to access h.style, but for me it doesn't work. My code:

<!DOCTYPE html>
<html>
<head>
    <title>
        DOM Manipulation Basics
    </title>
</head>
<body>
    <h1> Hello </h1>

</body>
</html>

Here's what happens in the console:

var h=document.getElementsByTagName("h1");
undefined
h
HTMLCollection [h1]0: h1length: 1__proto__: HTMLCollection
h.style;
undefined
h[0].style;
CSSStyleDeclaration {alignContent: "", alignItems: "", alignSelf: "", alignmentBaseline: "", all: "", …}
h.style.color="red";
VM999:1 Uncaught TypeError: Cannot set property 'color' of undefined
    at <anonymous>:1:14
(anonymous) @ VM999:1
h[0].style.color="red";
"red"
  • 2
    `h` is a `HTMLColletion` returned by `getElementsByTagName()` and not a single element. `style` is a property of `DOMElement` and not a property of `HTMLColletion`. Therefore you will need a loop to handle each `DOMElement` of the `HTMLColletion` separately. What your instructor could be doing (=assumption) is something like `var h=document.getElementsByTagName("h1")[0]` – Lain Jun 19 '20 at 08:43
  • your `h` is an array of objects. but you are using your `h` as an object. – Jovylle Jun 19 '20 at 08:44
  • getelements returns an array, you can select items in an array using the [] block quotes, [0] indicates the first item in the array wich is your h1 – Ramon de Vries Jun 19 '20 at 08:45

2 Answers2

1

getElementsByTagName() always returns an array consisting of all the elements with the matching tag name. Therefore 'h' contains an array an that is why h.style is not defined but h[0].style is defined.

Prachi
  • 51
  • 2
  • 1
    A note: [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Element/getElementsByTagName) says it returns a HTMLCollection, which in some ways is similar to but [not the same as an array](https://stackoverflow.com/q/15763358/1220550). – Peter B Jun 19 '20 at 09:17
1

when you are use many h1 tags then you gonna need to access every h1 tags. Beacause of that getElementsByTagName() returns every h1 tags in ARRAY. if you want to access an element privately, you can give id your h1 tag then use getElementById("id")

for example

var h = document.getElementById("privateTag");
console.log(h);
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1 id="privateTag">Hello</h1>
</body>
</html>
hlfbprince
  • 11
  • 3
  • Thank you for clarifying me in case of multiple h1 tags. Because I'm using just one h1 tag, I figured out that the problem was that getElementsByTagName() returns an array-like structure(HTML Collection), even if you have a single tag. – Tanveer Brar Jun 19 '20 at 14:28