简体   繁体   中英

Why I can't select an iframe via $('#iframeid') via jQuery?

I have a page with a iframe:

<iframe id="a"></iframe>

I have jQuery on it and when I use:

$('#a') or $('iframe#a') , I can't get the element. What I get is a [] exactly like I am querying a non-exist HTML node.

Update: I want to select the <iframe> tag and do something to it, for example, remove it or change its height. I am NOT going to control the HTML inside that iframe.

Thanks for any kind of tips.

This question is a good example of why it's so useful to show us all the relevant code in a fiddle. :)

Your JSFiddle: http://jsfiddle.net/t925e

As you note in the comments, you are using math.random() to append to the ID name. This is your issue.

Let's take a sample of what math.random() will return:

0.8400670071132481

So using that and appending it to your ID, you end up with this:

iframeid0.8400670071132481

Which is not a valid ID value (you can't have a period in your ID)

The other issue is that your jQuery selector is now looking for for something with an ID of "iframeid0" and a class of "8400670071132481"--which doesn't exist on your page.

I'm not sure why you need a random ID, but if you do, the solution is to get rid of the decimal in it. One easy way to accomplish this is to use math.floor() and a multiplier.

For example

var ss = Math.floor(1000*Math.random());

That will give you a random whole number between 0 and 999. Increase your multiplier if you need a larger range than that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM