문제

Here is my HTML:

<button class="btn" data-key="123456789">Show</button>
<button class="btn" data-key="abcdefghi">Show</button>

I also have iframes that have matching data-key attributes (i.e., for each button with a key there will be a corresponding iframe with the same key).

I need to grab the iframe with given key when the button with the corresponding key is clicked.

First I grab all the items with the given key:

var keyElems = document.querySelectorAll('[data-key="' + key + '"]');

This will return a nodelist with an iframe and button. Within keyElems I want to be able to just get the iframe element. Why can't I just do something like this?

var frame = keys.getElementsByTagName('iframe');

This doesn't seem to work, I'm assuming because keys is a nodelist. Is there a more elegant way to do this than just doing a loop and checking to see if the element is an iframe or not?

도움이 되었습니까?

해결책

You'd just have to modify your selector to pick iframe

var keyElems = document.querySelectorAll('iframe[data-key="' + key + '"]');

If you're only expecting one iframe to be returned, use querySelector instead. It returns the first element from a NodeList

다른 팁

document.querySelectorAll returns a nodelist, not a single HTML element, so it has no method querySelectorAll. In other words, you can't chain querySelectorAll method calls.

But then you've no need to; just modify your selector:

document.querySelectorAll('iframe[data-key="'+key+'"]');

For more complex purposes, where more computation is needed and merely extending the selector is not an option, you can harness array.prototype.filter

[].filter.call(document.querySelectorAll('[data-key="'+key+'"]'), function(el) {
    return el.tagName == 'iframe';
});
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top