Need help: document.getElementById().getElementsByTagName()

Can anyone tell me why this wouldn’t (and doesn’t) work?

document.getElementById("tableSelector").getElementsByTagName("table")[0].setAttribute("id","tableid"); 

By the way, Corporate Headquarters has programmers who write all the page-building stuff. When they are done, they send me the code to fix it. Convenient, eh? So although I wish I could change some of the processes, I have to deal with what they give me. In other words, I cannot change certain aspects, such as assigning random IDs to elements.

Context:

  • I am looking for a certain DIV on my page, and I can easily find it, since it has a known ID (tableSelector).
  • Inside that DIV is one table with a random ID that gets regenerated every time the page loads.
  • Although that table has a class, I cannot work with the CSS, because that class is global – and I only need to (or, I am only allowed to) make fixes to this one particular table.
  • So, I need to get that table’s random ID and replace it with an ID that I can add to the stylesheet.

Any suggestions, links or examples would be greatly appreciated. I have noodled around on this all morning, and I’m going slightly mad.

Let me say it in advance, thanks!

Are you running the script from the head section of the page?

Other than that, nothing appears to be “wrong” with the script, so that leaves us with a conflict in how it’s interacting with the HTML.

Please show us the HTML code that the script is supposed to be manipulating.

Thanks for you reply. I really appreciate it.

In a nutshell, it’s a PHP page that generates the classes, then a JS page constructs the whole page.

I think I have figured it out. Some of the elements aren’t on the page yet (haven’t loaded yet) when I make the calls. So I added a function that checks whether the elements exist, if not, setTimeout and try running the function again, until it works.

It’s a bit of a Neanderthal approach, but for now it will have to do.