0

I have the following code at https://jsfiddle.net/g6fqrxLz/, and rating.nextSibling seems is having problem getting the next sibling. I not sure what's the cause for this error

 <div class="star-rating">
   <div class="off">&#9733</div>
   <div class="off">&#9733</div>
   <div class="off">&#9733</div>
   <div class="off">&#9733</div>
   <div class="off">&#9733</div>
</div>
<input type="input" name="rating" class="rating-input" />

var rating = document.getElementsByClassName('star-rating')[0];
var ratingInput = rating.nextSibling;
alert(ratingInput.className);
user1187968
  • 7,154
  • 16
  • 81
  • 152
  • `getElementsByClassName()` returns a node list, not a single element. – Pointy Jan 09 '17 at 22:26
  • 1
    The next sibling after the
    is a TextNode containing the line break. It doesn't have a `className`, therefore you're getting `undefined`. One way to fix this is to put the `` immediately after the `
    `, not in the next line.
    –  Jan 09 '17 at 22:30
  • 2
    or use https://developer.mozilla.org/en-US/docs/Web/API/NonDocumentTypeChildNode/nextElementSibling and you got desired element: https://jsfiddle.net/g6fqrxLz/1/ – sinisake Jan 09 '17 at 22:31
  • 2
    @Pointy ... that's why the code uses `[0]` to get the first such item from the list - and `getElementsByClassName` returns an HTMLCollection, which is not quite the same as a NodeList :p – Jaromanda X Jan 09 '17 at 22:34
  • how did I miss that; I must need sleep or something – Pointy Jan 09 '17 at 22:49

0 Answers0