Is there a way I can pass the iframe src into a variable without using getElementById
?
I dont know the ID of the iframe as its dynamically generated – but I want to be able to check the src to see if it matches a defined string – the iframe has a class which I can target which is fancybox-iframe
I was hoping this would work but it does not:
var srcURL = document.getElementsByClassName('fancybox-iframe').src;
3
Answers
You can use the method
getgetElementsByTagName()
:Take care the name of this method is written in plural form so the result is an array, even the array will contain one element. That’s why the argument
[0]
is appended.returns an array of elements, so you should use
or better yet
https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName
https://developer.mozilla.org/en-US/docs/Web/API/Element/getElementsByClassName
Also you can use
Element.prototype.querySelector
andElement.prototype.querySelectorAll
to avoid filtering thegetElementsByClassName
result and get directly the iframes as soConfirmed in the comments:
iframe
sfancybox-iframe
You can select an iframe with a specific class using
then apply
.attr("src")
to get the source:This is in the format of
nodename.class
(without any spaces) which means the element must be of node type (iframe) and have the class (fancybox-iframe).You could probably also use
if that class is only used on that iframe.