jkj2000
jkj2000

Reputation: 1593

get a frame by its src property

I'm on a page with multiple iframes. I'd like to access one via javascript to manipulate some of the DOM elements on it.

Problem is, the iframe has no id or name attributes, just a src:

<iframe src="http://mysite/mypage/etc/etc/etc">divs and such in here</iframe>

I can't use document.getElementById('someframe').contentWindow.document.getElementById(...) in this instance since I don't have an ID to grab the frame by. Is there an XPath query or similar I can use in this case? (If it helps there's only one iframe here that has its source set to mysite/mypage.)

Upvotes: 1

Views: 400

Answers (1)

Simon Boudrias
Simon Boudrias

Reputation: 44619

You can use:

document.querySelector('iframe[src="http://mysite/mypage/etc/etc/etc"]')

This only work on modern browser. https://developer.mozilla.org/en-US/docs/Web/API/document.querySelector

For older browser support, select all iframe by tag names. Then recurse through all the elements you receive and check their src property.

A simple example: (code could and should be written better in your own implementation)

var iframes = document.getElementByTagName('iframe');
var matches = [];
for (el in iframes) {
    if (el.src === 'http://mysite/mypage/etc/etc/etc') {
        matches.push(el);
    }
}

Upvotes: 3

Related Questions