Chrome控制台无法定位到元素(提示undefined)

  在谷歌控制台输入js代码时,明明自己输入的是正确的代码,但是仍然提示“undefined”,若此时用检查元素小箭头定位一下该元素,再次使用js代码又发现可以定位到元素?

  往往此时我们应该想到页面代码中含有iframe,先要切换到对应的iframe,然后再次定位才能定位到。

  如图获取id=titles_div的div标签:

但是控制台中获取document.getElementById('titles_div')返回的事null

查看源代码,发现该标签处于

<iframe width="100%" id="mainFrame" frameborder="0" height="100%" style="border: none; padding: 0px; margin-top: 5px; height: 215px;" name="mainIFrame" border="0" src="modules/csh/csh_deposit_receipt.screen"> </iframe>

中,那么使用js代码时,需要首先切换到对应的iframe中才能定位到div标签:

doc = document.getElementById('mainFrame').contentWindow.document;
doc.getElementById('titles_div');

或者在chrome中控制台中切换iframe再定位:

 

posted @ 2019-07-26 15:37  smartsmile  阅读(1592)  评论(0编辑  收藏  举报