Jump to content
Kare

this Keyword

Recommended Posts

I quoted this code from "How to" section's "Accordion" part. There are 2 "this" keywords here and i'm trying to understand what they are referring to and how they work. Could someone explain please?

var acc = document.getElementsByClassName("accordion");
var i;

for (i = 0; i < acc.length; i++) {
  acc.addEventListener("click", function() {
    /* Toggle between adding and removing the "active" class,
    to highlight the button that controls the panel */

    this.classList.toggle("active");

    /* Toggle between hiding and showing the active panel */
    var panel = this.nextElementSibling;
    if (panel.style.display === "block") {
      panel.style.display = "none";
    } else {
      panel.style.display = "block";
    }
  });
}

Share this post


Link to post
Share on other sites

Inside the event handler, it refers to the element that fired the event.  So whatever element was clicked on.

Share this post


Link to post
Share on other sites

var panel = this.nextElementSibling;

What about "nextElementSibling"? I looked at its description and it gives the <ul> <li> example. But what's next sibling does it choose here in the above code and how does it work? Could you help please?

Share this post


Link to post
Share on other sites

It gets the next sibling of the element.  I don't know what element that is because I haven't seen the elements, just the Javascript.  Siblings are elements with the same parent.

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...

×
×
  • Create New...