Home > Software design >  Get the iframe src without using getElementById
Get the iframe src without using getElementById

Time:11-10

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;

CodePudding user response:

You can use the method getgetElementsByTagName():

srcURL = document.getElementsByTagName("iframe")[0].src;

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.

CodePudding user response:

Confirmed in the comments:

  • there's multiple iframes
  • only one has the class fancybox-iframe
  • jquery is already in use

You can select an iframe with a specific class using

$("iframe.fancybox-iframe")

then apply .attr("src") to get the source:

$("iframe.fancybox-iframe").attr("src")

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

$(".fancybox-iframe").attr("src")

if that class is only used on that iframe.

CodePudding user response:

Element.prototype.getElementsByClassName

returns an array of elements, so you should use

document.getElementsByClassName('fancybox-iframe')[0].src

or better yet

const elements = Array.from(document.getElementsByClassName('fancybox-iframe'))
  .filter(element => element.tagName.toLowerCase() == 'iframe');

if(!elements.length) {
  // handle no iframe.fancybox-iframe found
}

const src = elements[0].src

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 and Element.prototype.querySelectorAll to avoid filtering the getElementsByClassName result and get directly the iframes as so

const elements = Array.from(document.querySelectorAll('iframe.fancybox-iframe'))
  • Related