Home > Back-end >  Getting "undefined" error when using DOM in Javascript
Getting "undefined" error when using DOM in Javascript

Time:09-22

I have created a fuction updateCard(elem, name, role, bio), which takes in an element id to update, name, role, and bio as strings and changes the content on the screen. The complete HTML javscript code is:

    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta http-equiv="X-UA-Compatible" content="ie=edge" />
        <title>DOM</title>
      </head>
      <body>
        <section id="card">
          <h1>New Student</h1>
          <h3>Role</h3>
          <p>Bio Text Goes Here</p>
        </section>
    
        <script src="./index.js">
        function updateCard(elem, name, role, bio) {
  const card = document.getElementById(elem);
  const head = document.getElementsByTagName("h1");
  head.textContent = name;
}
          updateCard("card", "shantanu", "engineer", "just a normal person");
        </script>
      </body>
    </html>

CodePudding user response:

getElementsByTagName returns an array as in the name ELEMENTS.

just do head[0].innerHTML. It will work.

More info here:

The getElementsByTagName() method returns a collection of an elements's child elements with the specified tag name, as a NodeList object.

https://www.w3schools.com/jsref/met_element_getelementsbytagname.asp

CodePudding user response:

getElementsByTagName returns an array, you need to target first array element to update the value as described below. Similarly you can update your rest of the values. The full working example is added

head[0].textContent = name;

Working Code

function updateCard(elem, name, role, bio) {
  const card = document.getElementById(elem);
  const head = document.getElementsByTagName("h1");
  const roleTag = document.getElementsByTagName("h3");
  const bioTag = document.getElementsByTagName("p");
  head[0].textContent = name;
  roleTag[0].textContent = role;
  bioTag[0].textContent = bio;
}
updateCard("card", "shantanu", "engineer", "just a normal person");
<section id="card">
  <h1>New Student</h1>
  <h3>Role</h3>
  <p>Bio Text Goes Here</p>
</section>

CodePudding user response:

You get array from getElementsByTagName.

Do it like this: head[0].textContent = name;

  • Related