1

I want to check if there exists an element with a particular id inside a table, below is my code.

HTML:

<table id="age-table">
        <tr>
            <td id="age-header">Your age:</td>
            <td>
                <label>
                    <input type="radio" name="age" value="young"/> under 18
                </label>
                <label>
                    <input type="radio" name="age" value="mature"/> 18 to 50
                </label>
                <label>
                    <input type="radio" name="age" value="senior"/> after 60
                </label>
            </td>
        </tr>
    </table>

And script:

    <script>
        var table = document.getElementById('age-table');
        var lables = table.getElementsByTagName('label');
        console.log(lables);
        var findid = table.getElementById('age-header'); //throws error table.getElementById() is not a function.

    </script>

I can achieve what I want by using contains() like this

var id = document.getElementById('age-header');
var findid = table.contains(id);
console.log(findid);

But I didn't understand why table.getElementsByTagName('label') worked, but table.getElementById('age-header') threw error. Any insight will be greatly appreciated.

Thanks.

Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
Kumar Anand
  • 49
  • 1
  • 6

2 Answers2

3

The method getElementById is only available for the Document object. If you think about it, it makes sense, because IDs are supposed to be unique across a document, not a DOM element.

Have a look at this.

Maria Ines Parnisari
  • 16,584
  • 9
  • 85
  • 130
0

The document is the instance of HTMLDocument.

enter image description here

But the element (in your example, table) is the instance of HTMLDivElement.

enter image description here

You can easily check these prototype's different.

Alfred
  • 1,276
  • 11
  • 19