javascript - jQuery 从所有 iframe 中删除元素

标签 javascript jquery iframe

我有一个页面,其中包含 4 个 iframe。我想使用 jQuery(或纯 JavaScript)来循环所有这些 iframe(我不知道它们的 ID)和主框架,并删除具有指定类名的元素。我将调用此函数从 Chrome 扩展程序中删除这些元素。

我该怎么做?感谢您的回答。

最佳答案

使用这些函数,并将 '.class-name' 替换为您的类名(您可以使用任何 jQuery 选择器)。

var getIFrameDocument = function(iframe) {
    var doc;
    try {
        if ((typeof InstallTrigger !== 'undefined') && (iframe.contentDocument)) { // Firefox, Opera
            doc = iframe.contentDocument;
        } else if (iframe.contentWindow) { // Internet Explorer
            doc = iframe.contentWindow.document;
        } else if (iframe.document) { // Others?
            doc = iframe.document;
        }
    } catch(e) {
    }

    return doc;
};

var findElementRecursively = function(selector, doc) {
    try { /* Helps prevent errors like "Permission denied to access property 'jquery'" */
        var element = jQuery(selector, doc);
    } catch (e) {
        return null;
    }

    if (element.length !== 0) {
        return element;
    }

    try {
        if (doc && doc.location === 'about:blank') {
            return null;
        }
    } catch (e) {
    }

    try { /* Helps prevent errors like "Permission denied to access property 'jquery'" */
        var iframes = jQuery("iframe", doc);
    } catch (e) {
        return null;
    }

    var result = [];
    for (var i = 0; i < iframes.length; i++) {
        var iframeDoc = getIFrameDocument(iframes[i]);

        if (!(typeof(iframeDoc) === 'undefined')) {
            element = findElementRecursively(selector, iframeDoc);
            if (!(element === null)) {
                for (var j = 0; j < element.length; j++) {
                    result.push(element[j]);
                }
            }
        }
    }

    if (result.length > 0) {
        return jQuery(result);
    } else {
        return null;
    }
};

var element = findElementRecursively('.class-name', document);
if ((!(element === null)) && (element.length > 0)) {
    // element.remove(); // I'm not sure if this works.
    element.each(function() {
        jQuery(this).remove();
    });
}

关于javascript - jQuery 从所有 iframe 中删除元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26354717/

相关文章:

javascript - 如果下拉列表中只有一个值,则 HTML 下拉列表无法捕获 onChange()

jquery - Twitter bootstrap modal 落后于 iframe

javascript - 当我按下按钮时,如何在 div 中复制表单?

Javascript 和 CSS : how to get the value of the style sheet file?

javascript - setTimeout() 多次调用时仅运行一次

html - 使嵌入式网页适合浏览器窗口的宽度和高度?

css - 在 html 页面的容器中打开网站

javascript - 单击复选框更改 p 文本

jQuery - 多个相同 IF 条件的简写并同时匹配多个元素?

javascript - 查找下一个输入字段并在它为空时设置焦点-jquery