0

I'm very simply trying to add a class to the element .page-item-39 a using Javascript but i'm getting the error "Uncaught TypeError: Cannot read property 'className' of undefined", what is the reason for this?

var menuItem = document.getElementsByClassName('page-item-39');
  var menuLink = menuItem.firstChild;
  console.log(menuLink);
  menuLink.className += ' menu-item-active';
.menu-item-active {
    border: 1px red solid;
}
<li class="page_item page-item-39">
    <a>Classes</a>
</li>
CalAlt
  • 1,683
  • 2
  • 15
  • 29
  • you could just use the css psudo selecor `:nth-child(1)`. Aka: `page-item-39>:nth-child(1)` – Olian04 Dec 16 '17 at 15:48
  • If you want to add it to the *first* `.page-item-39 a` element: `document.querySelector(".page-item-39 a").className += " menu-item-active";` If you want to add it to all `.page-item-39 a` elements, you'll need to loop through the list returned by `getElementsByClassName` (or `querySelectorAll`, which would probably make more sense here as you want the `a` within the `.page-item-39`). – T.J. Crowder Dec 16 '17 at 16:06

1 Answers1

2

Use [0] instead of firstChild on menuItem.

var menuItem = document.getElementsByClassName('page-item-39');
  var menuLink = menuItem[0];
  console.log(menuLink);
  menuLink.className += ' menu-item-active';
.menu-item-active {
    border: 1px red solid;
}
<li class="page_item page-item-39">
    <a>Classes</a>
</li>
Mamun
  • 66,969
  • 9
  • 47
  • 59