以递归方式查找嵌套iframe中的给定元素*

Joe*_*ank 2 jquery jquery-selectors

什么是在当前文档中找到给定"div.myClass"元素的最佳方法,以及它(以及它们的嵌套iframe)可能具有的任何iframe?

谢谢

Rob*_*b W 6

如果帧访问不受同一原始策略的限制:

function getElem(selector, $root, $collection) {
    if (!$root) $root = $(document);
    if (!$collection) $collection = $();
    // Select all elements matching the selector under the root
    $collection = $collection.add($root.find(selector));
    // Loop through all frames
    $root.find('iframe,frame').each(function() {
        // Recursively call the function, setting "$root" to the frame's document
        getElem(selector, $(this).contents(), $collection);
    });
    return $collection;
}
// Example:
var $allImageElements = getElem('img');
Run Code Online (Sandbox Code Playgroud)