1

Sorry for a stupid question, but maybe someone can explain it to me. On w3school web-site you can find a modal example. And in order to close the modal they use the following line of code:

HTML:

<span class="close">&times;</span>

Script:

// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];

Why to use array here? I tried this code without this array and it doesn’t work. I tried to use different indexes in this array and it also doesn’t work.

Why do we use [0] here and how does it exactly work?

8
  • 2
    because its getElements ? so potentially more than one ... ??
    – WilomGfx
    Feb 17, 2018 at 13:10
  • But why does not simple getElement without an array work here? Feb 17, 2018 at 13:11
  • 2
    @VladNorton, I don't think you get it. Did you see the bold letter in Wilom's comment?
    – trincot
    Feb 17, 2018 at 13:12
  • Yes I see, I tried to use getElement. without S. And it simply doesn't work this way. Modal can't be closed Feb 17, 2018 at 13:14
  • Why did you think that method exists without s? Could you reference the documentation for it?
    – trincot
    Feb 17, 2018 at 13:15

2 Answers 2

1

According to Mozilla developer documentation, it returns an array of child elements.

Returns an array-like object of all child elements which have all of the given class names. When called on the document object, the complete document is searched, including the root node. You may also call getElementsByClassName() on any element; it will return only elements which are descendants of the specified root element with the given class names.

In your case, you have only one DOM element having class 'close'. That's why it returns an array of one element.

0

Because you can assign a class to more than one element in your HTML document. getElementsByClassName does exactly that: An array of all HTML elements which got the given class assigned to them. The [0] picks the first (and in your case only) element from that array.

If you want to give an unique identifier to a HTML element, assign an id to it and use getElementById.

<span id="close">&times;</span>

var span = document.getElementById("close");

Not the answer you're looking for? Browse other questions tagged or ask your own question.