DhavalR
DhavalR

Reputation: 1417

get element by id from parent tag

My DOM is as below.

<html><head>...</head><body><script>...</script>
<iframe id="frame">
    #document
    <html>...</html> <!-- 2 -->
</iframe>
</body>
</html>

I am binding partial in iframe (i.e. html 2). In html_2 partial, I am calling document.ready to get id of iframe using getElementById, but I am getting null. How to get id and other attribute values of iframe?

Upvotes: 0

Views: 2323

Answers (3)

DhavalR
DhavalR

Reputation: 1417

I did this as below,

$("#iframe", parent.document).attr("id");

BTW, Thanks all who answered and helped me by valued comments.

Upvotes: 1

philantrovert
philantrovert

Reputation: 10082

Try using this:

document.getElementById("frame").contentWindow.document.getElementById("div1")

Upvotes: 0

guradio
guradio

Reputation: 15555

$("iframe").each(function() {
  alert($(this).attr("id"));

})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>

<head>...</head>

<body>
  <script>
    ...
  </script>
  <iframe id="frame">

  </iframe>
  <iframe id="frame1">

  </iframe>
  <iframe id="frame2">

  </iframe>
</body>

</html>

  1. Use .attr("id")
  2. For multiple iframe use .each() to iterate iver all iframe
  3. Use this to get current iframe

Upvotes: 0

Related Questions