JS getElementById only visible after inspect element

Viewed 1454

I have a strange behavior where I have a code rendered in the main screen based on the HTML which is stored in the DB.

If I do getElementById(‘myGivenId’) in the console of the Chrome inspector I get null. However after I click on inspect element (anywhere on the screen), and try to fetch element again, it appears.

How can I make element 'findable' by default?

Section of the code:

<div class="hidden popupbox" data-contentid="666">
    <iframe width="16" height="9" src="//www.youtube.com/embed/...modestbranding=1" autohide="1"
                                frameborder="0" allowfullscreen="" class="video" id="myGivenId"></iframe>
</div>

Doing document.getElementById('myGivenId')

4 Answers

You can't get an element from inside an iframe when the iframe's src is from another domain, as you won't be able to access the content in the iframe due to Same Origin Policy.

if it's from the same origin you can get the element with contentWindow

There are several things that can cause this:

  • Invalid HTML, some tag is not closed or similar
  • Duplicate IDs
  • Maybe element you are trying to get by ID is created dynamically by a script?

Do they have css attribute of display: none;

Before you click and they appear? If so they will not be in the DOM and you cannot get them with getElementById.

If this is the case try to replace it with visability: hidden if that causes no probleem for your app.

Or add the getElementById after the class change to display the content.

But more info / code snippets would be helpfull

I'm having the same issue.

I've tried to check if a validation field is undefined or it has a text value. The point is that if I check in the console making different actions, I'm getting the same result, but if I inspect the element in the browser, it looks that is refreshing something and I'm getting the correct value. If you check the pic, I've got different values without touching anything in the workflow application.

Console inspection

Related