0

I am having an iframe inside a div element which is hidden/display none, I want to get the href attribute of a tag using javascript my code is

HTML

<div id="questions" style="display: none;">
    <iframe id="article_frame" width="100%" height="100%">
        <a href="someurl" id="en_link">Click here</a>
    </iframe>
</div>

JS

window.onload = function() {
    alert("Hello " + window.document.getElementById("article_frame"));
}

But I am getting alert as "Hello null" any solution

Thanks

Riyaz
  • 29
  • 8
  • 3
    The code in your post is only a pesudo-code, and you've the anchor in a real file loaded to the `iframe`? – Teemu May 22 '14 at 06:37
  • You want to display a list of `href` link inside an `iframe`? – jhyap May 22 '14 at 07:07
  • Please answer the question! At first, your HTML is invalid, secondly, `#article_frame` is the `iframe` you have, it shouldn't be `null`... – Teemu May 22 '14 at 10:53

3 Answers3

1

Thanks All,

I have got the answer with javascript it just simple code

var anchor = document.getElementById('en_article_link').firstChild;
var newLink = anchor.getAttribute("href")+"sid="+sidvalue;
anchor.setAttribute("href", newLink);
Riyaz
  • 29
  • 8
0

Ok i feel this may be a slight overkill but it will get you what you require (the href value of the anchor tag inside the iframe) :

window.onload = function() {

        var frame = window.document.getElementById("article_frame");

        var myString = frame.childNodes[0].textContent
          , parser = new DOMParser()
          , doc = parser.parseFromString(myString, "text/xml");

        var hrefValue = doc.firstChild.getAttribute('href');

        alert("Hello " + hrefValue);
}

I guess it depends on your requirements but another way would be to create a string and then using functions: substring and indexof you could get your value. Here is how you would get the string:

window.onload = function() {

        var frame = window.document.getElementById("article_frame");

        var elementString = frame.childNodes[0].textContent;
        //then perform your functions on the string here
}
EaziLuizi
  • 1,557
  • 1
  • 16
  • 25
-1

Note that you can only access the contents of an iframe that contains a page on the same domain due to the Same-Origin Policy (Wikipedia).

I recommend using jQuery for this. The tricks here are:

  1. Wait for the iframe to finish loading $("#article_frame").ready()
  2. Access the iframe's document $("#article_frame").contents()

From there you're just handling the task at hand:

$("#article_frame").ready(function() {
  alert("Hello " + $("#article_frame").contents().find("#en_link").href);
});
Anthony DiSanti
  • 516
  • 8
  • 9