sleepylog
sleepylog

Reputation: 67

Needing explanation for getElementsByClassName("className")[0];

In the javascript code further down, can someone please explain to me the purpose/meaning of [0] in the following line of code please? : var contactSpan = document.getElementsByClassName("close")[0];

I understand how all of the code works except for that part. I have included relevant html code linked to that part of my js code for clarity's sake.

I'm fairly new to web coding so please don't use overly technical language if it can be avoided. Thank you:)

<div class="collapse navbar-collapse" id="bs-nav-demo">
          <ul class="nav navbar-nav navbar-right">
            <li><a href="#" id="contact">Contact</a></li>
          </ul>
        </div>

<div id="contactModal" class="modal">
  <div class="modal-content">
    <span class="close">&times;</span>
      <p>Contact details here</p>
  </div>
</div>

javascript:

// Get the button that opens the modal
var contact = document.getElementById('contact');

// Get the modal
var contactModal = document.getElementById('contactModal');

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

Upvotes: 0

Views: 2589

Answers (2)

anees
anees

Reputation: 1855

That is why there could be more than one elements containing same class but ids are unique. So in DOM you have to define exactly what element you want to access. Like if there are two elements using same class like

<div class="sample">Bla Bla Bla</div>
<div class="sample">No Bla Bla</div>

Then document.getElementsByClassName("sample")[0]; is the first element (at 0 index of array like object) having that class and document.getElementsByClassName("sample")[1]; is the second element having that class.

Upvotes: 2

Suren Srapyan
Suren Srapyan

Reputation: 68655

getElementsByClassName according to the plural form of Elements returns an array-like object. There may be more than one element with the class close, so why it returns array-like object.

Array or array-like object items can be access using the index of the item which starts from 0.

You have only one element in your page and your array-like object contains only one item, anyway it returns an array-like object with one item.

After that you are trying to get the first item using the [] index notation which is the current span element.

Last line of your code is equivalent to this two statements

var elemetsWithClassClose = document.getElementsByClassName("close");
var contactSpan = elemetsWithClassClose[0];

Upvotes: 1

Related Questions