当不知道嵌入对象的 id 时如何获取它?
我的html有一个被其他应用程序嵌入的扩展:
document.documentElement.appendChild((function () {
var objectElement = document.createElement("embed");
objectElement.setAttribute("id", "my-plugin");
objectElement.setAttribute("type", "application/x-my-app");
objectElement.setAttribute("width", "0");
objectElement.setAttribute("height", "0");
return objectElement;
}()));
通常我们通过它的id获取这个对象: var plugin = document.getElementById("my-plugin");
这里的问题是,对象被注入由其他应用程序执行,其 ID 可能会有所不同。我只知道它的 MIME 类型是“x-my-app”,但看起来没有 getElementByType()
来获取它?
My html has an extension which embeded by other application:
document.documentElement.appendChild((function () {
var objectElement = document.createElement("embed");
objectElement.setAttribute("id", "my-plugin");
objectElement.setAttribute("type", "application/x-my-app");
objectElement.setAttribute("width", "0");
objectElement.setAttribute("height", "0");
return objectElement;
}()));
Normally we get this object by its id: var plugin = document.getElementById("my-plugin");
The problem here is, the object is injected by other apps and its ID could vary. I only know its MIME type is "x-my-app", but looks like there is no getElementByType()
to get it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在足够高级的浏览器上,您可以使用
querySelector()
/querySelectorAll ()
:如果使用 jQuery,即使在不太先进的浏览器上,以下内容也将起作用:
如果两者都不是,您可以循环遍历所有
标记:
jsFiddle 示例 这三个。
On sufficiently advanced browsers you can use
querySelector()
/querySelectorAll()
:If using jQuery, the following will work even on less sufficiently advanced browsers:
If neither, you can loop over all the
<embed>
tags:jsFiddle example of all three.
您必须根据标签类型
embed
以及您所了解的相关信息来找到它。例如,如果您的 HTML 是这样的,其中嵌入 ID 未知:那么,您会发现它是这样的:
如果您正在查找的范围内有多个嵌入,那么您可能必须循环遍历所有找到的嵌入并检查嵌入标签的某些属性可识别您要查找的标签。
如果您向我们展示相邻的 HTML 是什么样的,我们就可以准确地找到您的调整方式。
You will have to find it based on tag type
embed
and the things you do know around it. For example if your HTML was like this where the embed ID us unknown:Then, you would find it like this:
If there are multiple embeds within the scope you're looking, then you may have to loop through all that are found and examine some attribute of the embed tag to identify the one you're looking for.
If you show us what the neighboring HTML is like, we could find tune exactly how you would fine it.
您可以使用
getElementsByTagName()
并循环遍历结果,直到找到具有正确媒体类型的结果。You can use
getElementsByTagName()
and loop through the results until you find one with the correct media type.