如何通过JavaScript/JQuery定位无ID指定iframe并获取内部数据?
Fixing Access to Iframe Content (No IDs, Local HTML Source)
Got it, let's walk through what's wrong with your original code and fix it so you can grab that div.entry-content from the second iframe (index 1).
First, Why Your Original Code Failed
Your code has two key issues:
- You used
$('ifrm')which is trying to select an HTML tag named<ifrm>(which doesn't exist!). You should instead wrap the already-selected iframe DOM element in jQuery:$(ifrm). - You didn't account for the iframe's load state. If you try to access the iframe's contents before it finishes loading, the DOM inside won't be ready yet, so your
find()call will return nothing.
Working jQuery Solution
Since your iframe is a local HTML file (same origin, no cross-domain restrictions), we can safely access its contents once it's loaded. Here's the corrected code:
// Grab the second iframe (index 1) var ifrm = document.getElementsByTagName('iframe')[1]; // Alternatively with jQuery: var ifrm = $('iframe')[1]; // Wait for the iframe to fully load before accessing its contents $(ifrm).on('load', function() { // Get the iframe's internal document var $iframeContents = $(this).contents(); // Find the target div inside the iframe var $entryContent = $iframeContents.find('div.entry-content'); // Now you can use the content however you need console.log('Text content:', $entryContent.text()); console.log('HTML content:', $entryContent.html()); });
Pure JavaScript Alternative (No jQuery)
If you prefer vanilla JS, this works too:
var ifrm = document.getElementsByTagName('iframe')[1]; // Listen for the iframe's load event ifrm.addEventListener('load', function() { // Get the iframe's document object (handles cross-browser compatibility) var iframeDoc = this.contentDocument || this.contentWindow.document; // Find the target div var entryContent = iframeDoc.querySelector('div.entry-content'); if (entryContent) { console.log('Text content:', entryContent.textContent); console.log('HTML content:', entryContent.innerHTML); } else { console.log('Target div not found in iframe'); } });
Key Notes
- Same Origin Policy: Since your iframe's source is a local HTML file (no external links), you won't hit cross-domain restrictions. This code only works if the iframe and parent page are from the same origin (which they are here).
- Load Event: Always wait for the
loadevent to fire—this ensures the iframe's internal DOM is fully rendered and ready to be queried.
内容的提问来源于stack exchange,提问作者Jeevan kumar
相关产品推荐
相关产品推荐

