-5

I have a code in the snippet that has a document.getElementsByClassName("close")[0], what the [0] is doing?

I never seen a square brackets being used in getElementsByClassName for what purpose is it used for?

Also, how can I convert it to jQuery?

var modal = document.getElementById("myModal");
var btn = document.getElementById("myBtn");
var span = document.getElementsByClassName("close")[0];

btn.onclick = function() {
  modal.style.display = "block";
}
span.onclick = function() {
  modal.style.display = "none";
}
window.onclick = function(event) {
  if (event.target == modal) {
    modal.style.display = "none";
  }
}
body {font-family: Arial, Helvetica, sans-serif;}

.modal {
  display: none;
  position: fixed;
  z-index: 1;
  padding-top: 100px;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  overflow: auto;
  background-color: rgb(0,0,0);
  background-color: rgba(0,0,0,0.4);
}

.modal-content {
  background-color: #fefefe;
  margin: auto;
  padding: 20px;
  border: 1px solid #888;
  width: 80%;
}

.close {
  color: #aaaaaa;
  float: right;
  font-size: 28px;
  font-weight: bold;
}

.close:hover,
.close:focus {
  color: #000;
  text-decoration: none;
  cursor: pointer;
}
<h2>Modal </h2>

<button id="myBtn">Open Modal</button>

<div id="myModal" class="modal">
  <div class="modal-content">
    <span class="close">&times;</span>
    <p>Some text in the Modal..</p>
  </div>
</div>
MestreALMO
  • 141
  • 4
  • 14
  • It's the syntax for retrieving a value in an array by its index. In this case the index is 0, or the first item in the array. Or https://developer.mozilla.org/en-US/docs/Web/API/HTMLCollection as I believe that's what `getElementsByClassName` retrusn. – Derek Dec 24 '21 at 20:42
  • @Derek it returns an HTMLCollection – yaakov Dec 24 '21 at 20:42
  • 1
    These are [Property accessors](//developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Property_Accessors). – Sebastian Simon Dec 24 '21 at 20:48
  • For JQuery ... `$('.close').first().hide() // or show()` – charlietfl Dec 24 '21 at 20:51

1 Answers1

2

document.getElementsByClassName returns array-like object of elements.

[0] takes first element of that array.

Basically:

let elements = document.getElementsByClassName('close');

let span = elements[0];
Justinas
  • 41,402
  • 5
  • 66
  • 96