Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
How to loop through all the iframes elements of a page using jQuery?
To loop through all the iframe elements of a page, use the jQuery each() method. The each() method iterates over a jQuery object, executing a function for each matched element. This is particularly useful when you need to perform operations on multiple iframes or extract information from them.
Example
You can try to run the following code to learn how to loop through all iframes. We have created three iframes below −
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("iframe").each(function(index){
var src = $(this).attr('src');
var title = $(this).attr('title') || 'No title';
alert("iframe " + (index + 1) + ": " + title + " - " + src);
});
});
});
</script>
</head>
<body>
<iframe src="https://www.qries.com" title="Qries Q/A"></iframe>
<iframe src="https://tutorialspoint.com" title="Tutorialspoint Free Learning"></iframe>
<iframe src="https://sendfiles.net" title="Send Files"></iframe>
<br>
<button>Loop through iframes</button>
</body>
</html>
Alternative Approach with Different Operations
You can also perform different operations while looping through iframes, such as modifying attributes or collecting data −
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#countBtn").click(function(){
var count = 0;
$("iframe").each(function(){
count++;
$(this).css('border', '2px solid red');
});
alert("Total iframes found: " + count);
});
});
</script>
</head>
<body>
<iframe src="https://www.example1.com" width="200" height="100"></iframe>
<iframe src="https://www.example2.com" width="200" height="100"></iframe>
<br>
<button id="countBtn">Count and Highlight iframes</button>
</body>
</html>
The each() method provides an efficient way to iterate through all iframe elements and perform operations on each one, making it a valuable tool for dynamic web page manipulation.
