Search code examples
javascriptgetelementsbyname

getElementsByName not working


Looked up several "Answers" to this problem, but it was mostly just people not treating the result returned by getElementsByName() as a NodeList!

Edit: I am trying to hide/show elements based on an element being clicked. I could hardcode this using document.getElementById and just add one everytime I have an element I want to hide/display. But it would be ideal if I could retrieve all elements named something and just run a loop on them to hide/show. Then I could just tag an element with a name when writing and this loop would work without alteration. Below my code is simply trying to popup an alert with the value for testing purposes. As for now, it consistently breaks with a null error. I am using and designing for internet explorer 9 as this is what the company uses.

Code:

    <input type="radio" name="Area" value="Engineering" id="EngineeringCheck" onclick="javascript: ShowContentEngineering();" />Engineering

<script type="text/javascript">
    function ShowContentEngineering() {
        alert(document.getElementsByName('EngineeringAreas')[0].value)
        document.getElementById('InformationBlock').style.display = 'block';
}
</script>

<h5 name="EngineeringAreas" value="luls"> WHAT THE HECK </h5>

Code above breaks saying that the object at getElementsByName('EngineeringAreas')[0] is null. Clearly, right below it, it is not null... Am I confusing getElementsByName('string')[0].value with the value of the element? Or is it retrieving some other value?

Ideally, I'd add other elements later, tag them with "EngineeringAreas" and never have to mess with the hide/show function.

Edit: Here is the error message:

Unhandled exception at line 53, column 9 in http://localhost:57264/Home/Index

0x800a138f - Microsoft JScript runtime error: Unable to get value of the property 'value': object is null or undefined

Solution

  • Here you go... seems:

    1. onclick="javascript: <--- not necessary - just reference the function name
    2. ShowContentEngineering needs to be set in the window context
    3. You're referencing the "value" attribute of an element that doesn't allow value attributes (h5)

    I made it work instead grabbing the innerHTML of the h5 Code

    <input type="radio" name="Area" value="Engineering" id="EngineeringCheck" onclick="ShowContentEngineering();" />Engineering
    
    <h5 name="EngineeringAreas"> WHAT THE HECK </h5>
    <script>
        window.ShowContentEngineering = function() {
            alert(document.getElementsByName('EngineeringAreas')[0].innerHTML)
            document.getElementById('InformationBlock').style.display = 'block';
        }
    </script>
    

    Here's a working fiddle: https://jsfiddle.net/mu970a8k/