Ramakanth Reddy
Ramakanth Reddy

Reputation: 139

travesing through ids in Html

I have an issue. I have two different main div elements with same sub div elements.

when i want to get table like

table = document.getElementById('list_table');

THis is giving me 1st div table data but i want second div table info.

Can anyone please help me with this. I can not change id names.

Thank you

<div id="container_1">
    <div id="my_table">
        <table id = "list_table"> 
        </table        
    </div>
</div>

<div id="container_2">
    <div id="my_table">
        <table id = "list_table"> 
        </table        
    </div>
</div>

Upvotes: 1

Views: 65

Answers (2)

Volod
Volod

Reputation: 1437

You should avoid situations with same id. But If you realy can do nothing about it here is workaround:

table = document.querySelectorAll('#list_table');

Will return

NodeList(2) [table#list_table, table#list_table]
0:table#list_table
1:table#list_table

https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll

Upvotes: -1

Nick
Nick

Reputation: 3961

The id global attribute defines a unique identifier (ID) which must be unique in the whole document. source

Use class:

table = document.getElementsByClassName('list_table')[1];

Upvotes: 5

Related Questions