skip to Main Content

I want to do something like this:

<div id="parent">
  <iframe id="myFrame" title="HEY!" srcdoc="<div id='inner'>Hello World!</div>"></iframe>
</div>
var parent = document.getElementById("parent").innerHTML;
var title = parent.getElementById("myFrame").title;

But this throws an error like innerHTML doesn’t have getElementById attribute.
How can I get the title of the iframe element in the innerHTML.
Note: It must be inside the innerHTML element.

2

Answers


  1. Try this,

    var parent = document.getElementById("parent");
    
    var title = parent.querySelector("#myFrame").title;
    
    Login or Signup to reply.
  2. First of all, the .innerHTML returns a string, not a DOM element. So as many suggested, you should remove this.

    var parent = document.getElementById("parent");
    var title = parent.getElementById("myFrame").title;
    <div id="parent">
      <iframe id="myFrame" title="HEY!" srcdoc="<div id='inner'>Hello World!</div>"></iframe>
    </div>

    BUT THIS NOT ONLY OUTPUTS AN ERROR, BUT IT ALSO DOESN’T WORK !

    It would for getElementByClassName() and getElementByTagName(), but that’s not the point…

    You are running the getElementById() method on an element, and this doesn’t work : why would you run this method scoped ? what’s the point as IDs have to be unique (but not classes or tags) ?

    So here, this is enough :

    var title = document.getElementById("myFrame").title;
    console.log(title);
    <div id="parent">
      <iframe id="myFrame" title="HEY!" srcdoc="<div id='inner'>Hello World!</div>"></iframe>
    </div>

    EDIT :
    Just to make things clear :

    You can only call getElementByID() on document as discussed here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search