'Selecting div inside iframe with jQuery
I am trying to select a div inside an iframe with jQuery. But I can't get it to work. Any suggestions what could be the issue here?
Parent HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<link rel="stylesheet" href="css/style.css" />
<title>Selector</title>
</head>
<body>
<iframe src="https://[sameDomainAsParent]/selector/template.html" id="selectorFrame"></iframe>
<script>
$("#selectorFrame").contents().find("#name").css("border", "2px solid red");
</script>
</body>
</html>
iframe HTML:
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="css/style.template.css">
<title>Template</title>
</head>
<body>
<div id="logo"></div>
<div id="color"></div>
<div id="name">Name</div>
<div id="title">Title</div>
</body>
</html>
Solution 1:[1]
I found the solution. I needed to wait for the iframe to be loaded. So the final jQuery script will be:
$(function() {
$("#selectorFrame").bind("load",function(){
$("#selectorFrame").contents().find("#name").css("border", "2px solid green");
});
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Michael Torp |
