英文:
How can I get an element with getElementById found in innerHTML
问题
我想要做类似这样的事情:
<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;
但这会报错,似乎 innerHTML 没有 getElementById 属性。
如何在 innerHTML 中获取 iframe 元素的 title。
注意:它必须位于 innerHTML 元素内部。
英文:
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.
答案1
得分: 1
首先,.innerHTML
返回的是一个字符串,而不是一个 DOM 元素。因此,正如许多人建议的那样,你应该移除这部分。
var parent = document.getElementById("parent");
var title = parent.getElementById("myFrame").title;
但这不仅会导致错误,而且它也不起作用!
对于 getElementByClassName()
和 getElementByTagName()
来说会起作用,但这不是重点…
你正在在一个元素上运行 getElementById()
方法,这不起作用:为什么要在这个方法上使用作用域?ID 必须是唯一的(但类和标签不必如此)。
所以,在这里,只需要这样:
var title = document.getElementById("myFrame").title;
console.log(title);
编辑:
只为了明确一点:
你只能在 document
上调用 getElementByID()
,如这里所讨论的。
英文:
First of all, the .innerHTML
returns a string, not a DOM element. So as many suggested, you should remove this.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
var parent = document.getElementById("parent");
var title = parent.getElementById("myFrame").title;
<!-- language: lang-html -->
<div id="parent">
<iframe id="myFrame" title="HEY!" srcdoc="<div id='inner'>Hello World!</div>"></iframe>
</div>
<!-- end snippet -->
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 :
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
var title = document.getElementById("myFrame").title;
console.log(title);
<!-- language: lang-html -->
<div id="parent">
<iframe id="myFrame" title="HEY!" srcdoc="<div id='inner'>Hello World!</div>"></iframe>
</div>
<!-- end snippet -->
EDIT :
Just to make things clear :
You can only call getElementByID()
on document
as discussed here
答案2
得分: 0
尝试这样做,
var parent = document.getElementById("parent");
var title = parent.querySelector("#myFrame").title;
英文:
Try this,
var parent = document.getElementById("parent");
var title = parent.querySelector("#myFrame").title;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论