user967451
user967451

Reputation:

How to select this element in JavaScript?

I can't modify the following html:

<iframe src="http://google.com/foo" width="600" height="338" frameborder="0" webkitAllowFullScreen allowFullScreen></iframe>
<div style="padding:5px 0; text-align:center; width:600px;"><p>
<a href="http://www.foobar.com/lol/wut">Some Link</a></p></div>

I need to target this element:

<a href="http://www.foobar.com/lol/wut">Some Link</a>

The requirements are:

Since I can't edit the html I can't simply add an id and use document.getElementById. So how can I target the link using just plain js?

Upvotes: 0

Views: 244

Answers (3)

Ryan O&#39;Neill
Ryan O&#39;Neill

Reputation: 3757

function aSrcAfterIFrame(document) {
    var elements, result, looking, item, tagName, i, n;
    elements = document.getElementsByTagName('*');
    looking = false;
    for (i = 0, n = elements.length; i < n; i++) {
        item = elements[i];
        tagName = item.tagName.toLowerCase();
        if (looking && tagName === 'a') {
            result = item.href;
            break;
        }   
        if (tagName === 'iframe') {
            if (item.src.indexOf('http://google.com/foo') === 0) {
                looking = true;
            }   
        }   
    }   
    return result;
}

aSrcAfterIFrame(document);
"http://www.foobar.com/lol/wut"

Upvotes: 0

dennmat
dennmat

Reputation: 2718

READ EDITS.

Untested but assuming you're using jQuery something like this should do the trick.

var link = null;
$('iframe:first').siblings().each(function() {
    if (link !== null) return;
    if ($(this).attr('href') && $(this).attr('href').search('http://www.google.com') > -1) {
        link = $(this);
    }
});

Not the best solution, however I feel like this is an odd scenario.

EDIT: If Bergis selector works use that. Fancy stuff, I just learned something.

EDIT 2: Also I just noticed you wanted to check the iframe src not the link source so my post is essentially just plain wrong.

Upvotes: 0

Bergi
Bergi

Reputation: 665455

Check out selectors, especially attribute selectors and sibling combinators:

iframe[src^="http://google.com"] ~ a

You can easily use that in a jQuery selector expression or document.querySelector.

Upvotes: 2

Related Questions