skip to Main Content

I am trying to find all HTML tags with a specific name "name" inside an element with a specific id.

document.getElementById("myid").getElementsByName("name");

throws error getElementsByName is not a function

The sample code is:

<!DOCTYPE html>
<html>
  <body>
    <div id="myid">
        <p name="name">first name</p>
        <p name="name">first name</p>
    </div>
    <p id="result">RESULT</p>
  <script>
    let el = document.getElementById("myid")
    let names=el.getElementsByName("fname");
    document.getElementById("result").innerHTML = elements[0].innerHTML;
  </script>
  </body>
</html>

I saw somewhere that unlike other functions the ‘getElementsByName’ is limmited to ‘Document’ scope only and does not exist in any other scope.

  1. is this true?
  2. what alternative approach should I use instead of ‘getElementsByName’?

2

Answers


  1. To answer the questions:

    1: is this true?

    Yes

    2: what alternative approach should I use instead of ‘getElementsByName’?

    The alternative approach to document.getElementById("myid").getElementsByName("name"); would be

    document.querySelectorAll('#myid [name="name"]')

    3: The alternative to the code fragment would be

    <!DOCTYPE html>
    <html>
      <body>
        <div id="myid">
            <p name="name">first name</p>
            <p name="name">first name</p>
        </div>
        <p id="result">RESULT</p>
      <script>
        let el = document.getElementById("myid")
        let names=el.querySelectorAll('[name="fname"]');
        document.getElementById("result").innerHTML = elements[0].innerHTML;
      </script>
      </body>
    </html>
    

    4: I don’t see what elements even is, I guess it’s meant to be names[0].innerHTML

    Login or Signup to reply.
    1. yes
    2. you could use querySelector

    and keep in mind, that the attribute name is usually used on formular elements. In your case I’d suggest using class:

     <p class="name">first name</p> 
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search