user3810691
user3810691

Reputation: 531

contents() returns empty while contentDocument works

I'm struggling with a complex page to select few elements. The main one is a form where I need to read/change some values on the inputs. So far I'm successfully getting to form using this code:

var mainFrame = $(frames[1].document.body).contents().find("#mainFrame1");

ok, so I try:

$(mainFrame.contents());

and it returns empty []... if I try

$(mainFrame[0].contents());

I get error: mainFrame[0].contents is not a function...

But working with pure JS:

mainFrame[0].contentDocument.getElementById("dataForm");

works! I want to keep it into jQuery, and I need to find a few more elements inside this same frame, so I need the mainFrame variable be available for searching all this elements...

Trying to help the answer below find a complete solution I'm posting the console.debug for the mainFrame variable:

console.debug(mainFrame);
[frame#mainFrame, prevObject: b.fn.b.init[7], context: frameset#outerFrameSet, selector: "#mainFrame"]
0: frame#mainFrame
    accessKey: ""
    attributes: NamedNodeMap
    baseURI: "https://edited"
    childElementCount: 0
    childNodes: NodeList[0]
    children: HTMLCollection[0]
    classList: DOMTokenList[0]
    className: ""
    clientHeight: 369
    clientLeft: 0
    clientTop: 0
    clientWidth: 1150
    contentDocument: document
                             ->body
                                   ->children (here I can see the form I'm trying to select)
    contentEditable: "inherit"
    contentWindow: Window
    dataset: DOMStringMap
    dir: ""
    draggable: false
    firstChild: null
    firstElementChild: null
    frameBorder: "0"
    hidden: false
    id: "mainFrame"
    innerHTML: ""
    innerText: ""
    isContentEditable: false
    ...
    outerHTML: "<body ..."
    continues...

Upvotes: 2

Views: 2787

Answers (1)

KingCodeFish
KingCodeFish

Reputation: 342

$(mainFrame.contents()); works because mainFrame is a jQuery object. jQuery methods can only be applied to jQuery objects.

$(mainFrame[0].contents()); produces an error because mainFrame[0] returns a DOM node from the mainFrame jQuery object. Thus, you can't use $.contents on it.

To fix this we can rewrite it like so:

$(mainFrame[0]).contents();

This takes the DOM node and converts it back into a jQuery object, thus allowing us to run $.contents(); on it. Now obviously this can get messy when trying to use all that as another jQuery object like so: $($(mainFrame[0]).contents());. Because of some of this, you have methods like $.first(); instead of an array returning a DOM node. You also have the CSS :first-child selector.

Ultimately, to use $.contents(); you have to be using a jQuery object against it, not a DOM node which mainFrame[0] returns. Your final JavaScript version worked because JS's functions are built to work with DOM nodes, jQuery works with objects though.

Upvotes: 3

Related Questions