How can I get my baby name generator to get results?

How can I get my baby name generator to get results? Also, how would I control the style of the results, what do I target?

codepen

I was following a tutorial…and this is my first time using javascript. Help is supremely tremendously expeditiously appreciated.

Well, opening up the console, the first error I encounter is:

Uncaught TypeError: document.getElementByClassName is not a function
at pen.js?key=pen.js-b83afbcb-08be-7131-e89d-77eb35dc9402:14

It’s trying to tell you what one of the problems is.

1 Like

By changing these lines:

    const setRandomName = () => {
      document.getElementById('random-name').innerText = getRandomName();
    };

    const elements = document.getElementsByClassName('generate')
    for (var i = 0; i < elements.length; i++) {
      elements[i].addEventListener('click', setRandomName);
    }

And changing your html to:

        <div id="random-name"
 class="random-name"></div>

I was able to get it to work.

Keep in mind that there is no method “getElementByClassName”, there is “getElementsByClassName”, but that returns an array.

1 Like

I might also put in a plug for the FCC curriculum here - it teaches this stuff.

1 Like

One way to help remember this.

Each id should only be used one time so it’s Element. For classes, there can be many elements with the same class name so it is Elements. This is also why the two methods do not return the same things (Element object vs HTMLCollection).

getElementById
getElementsByClassName

Or you can just use querySelector and querySelectorAll using a selector string (same as what the CSS selector would be).

They are in my opinion a cleaner API and the NodeList returned by querySelectorAll has the forEach method on it (except in old browsers).

const setRandomName = () => {
  document.querySelector(".random-name").innerText = getRandomName();
};

document
  .querySelectorAll(".generate")
  .forEach((btn) => btn.addEventListener("click", setRandomName));
1 Like

@lasjorg Can you recommend an API tutorial for beginners? :slight_smile: