PGilm PGilm - 4 years ago 314
Javascript Question

get index of element selected by Document.getElementByID("id_name")

For a page ("Bill4Time"), the Dashboard shows a table for displaying time entries and entering a new time entry but several control elements do not have ID's associated with them. Interestingly enough, the control to add a new time entry line (an icon of a clipboard with a small plus sign in the lower right hand corner) always has the same index number (so I can select it with

Document.all("index_no")
to add a new time entry. But once you edit that line by entering a new time entry, the control icon changes (to a generic clipboard, like all the other time entries in the table) and the index becomes dynamic -- and there is no id associated with that control. However, I found that the parent element (i.e., the table cell) does have a unique ID which never changes (while it is the most recently added time entry) so currently I go to it (using
Document.getElementByID("unique_id").focus()
) and then send a {tab} to move over to the control element (and send {enter} to go to the correct details page).

If I could get the index number of the unique_id element, and increment that by one, I could more reliably get to the control I want, so my question is, if one has gotten a DOM element by id, how can one find its index number?

When I search here (or google) I get a lot of results for finding the index of the included elements within the parent, or results based on .selectedIndex and the like, and I suppose I could loop through all the DOM elements until I find the one with
ID = unique_id
, but there should be a better way to get an index number of a selected element.

TIA,

Answer Source

At least if doing it with IE and AutoHotkey this will give you the index

index := wb.document.getElementByID("unique_id").sourceIndex

But you don't need the index if you have the parent element

element := wb.document.getElementByID("unique_id").childnodes[0]

Also a lot of times elements that don't have an ID often have a Name or Class attribute, both of them can also be used to find the element you need...

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download