Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change iframe attribute with jquery

I have something like so:

        <iframe id="frame" width="200" height="150" 
    src="http://www.youtube.com/embed/GiZGEFBGgKU?rel=0&
amp&iv_load_policy=3;autoplay=1" frameborder="0" allowfullscreen></iframe>

And I want to change the width and height using jquery I try:

$("#frame").setAttribute("width", "50");
$("iframe").setAttribute("width", "31");

None of them work

like image 985
Ben Avatar asked Apr 10 '12 05:04

Ben


2 Answers

As Sarfraz already pointed out, the correct way to set the attribute for a jquery selector object is by using the attr("attrName", "attrVal"). The reason the setAttribute didn't work is something worth explaining, as I've hit my head against this point on more than one occasion:

When you use jquery's selector syntax, it returns an object -- defined in jquery -- which is essentially a list of all of the elements that the selector matched. Whether it matches one element (which should always be the case with an id selector) or more than one, the returned object is the element list, never a single DOM object (eg single element). setAttribute is a method for actual HTMLElement objects.

This is why

$("#frame")[0].setAttribute("width", "200");

works, but

$("#frame").setAttribute("width", "200");

does not. The jquery element does not have that method, even though the HTMLElement objects in its list do.

If you wanted to (for whatever reason) use a native HTMLElement method (or a method common to the elements your selector returns, such as inputs, etc), you can use jquery's each() method, like so:

 // Set all iframes to width of 250
 $("iframe").each(
     function(index, elem) {
         elem.setAttribute("width","250");
     }
 );

The each() method's callback can be passed two optional parameters, the first being the index of the element in the selector list, the second being the actual DOM element, which you can call native DOM methods on.

Like I said, I've gotten really frustrated trying to figure out how to use jquery's selector results with native methods more than once, so I hope this helps clear up not only why setAttribute() doesn't work, but native methods in general, and how to actually get them to work when you can't find the jquery equivalent.

like image 102
Anthony Avatar answered Sep 21 '22 13:09

Anthony


What about:

$('#frame').width(x)

or

$('#frame').attr("width","50");
like image 40
elclanrs Avatar answered Sep 24 '22 13:09

elclanrs