简体   繁体   中英

Cannot access innerHTML of span tag

I have this piece of code:

var size = iframe.contentWindow.document.getElementsByClassName('checked').getElementsByTagName('span')[0].innerHTML;            

For some reason every time I run it I get this message:

Uncaught TypeError: Object [object NodeList] has no method 'getElementsByTagName'

Even though all my other functions with getElementsByTagName() work fine. What could be the reason for this error?

Thanks

getElementsByClassName returns a set of elements (ie NodeList ), not a single element:

iframe
    .contentWindow
    .document
    .getElementsByClassName('checked')[0]  // <--- [0] (or whatever index)
    .getElementsByTagName('span')[0]
    .innerHTML;  

Besides you can replace it with querySelector :

iframe
    .contentWindow
    .document
    .querySelector(".checked span")
    .innerHTML;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM