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.
- is this true?
- what alternative approach should I use instead of ‘getElementsByName’?
2
Answers
To answer the questions:
Yes
The alternative approach to
document.getElementById("myid").getElementsByName("name");
would bedocument.querySelectorAll('#myid [name="name"]')
3: The alternative to the code fragment would be
4: I don’t see what
elements
even is, I guess it’s meant to benames[0].innerHTML
querySelector
and keep in mind, that the attribute
name
is usually used on formular elements. In your case I’d suggest using class: