tags:

views:

70

answers:

2

I have a div in a page that I can't select with jQuery. I've tried selecting by ID and by class, with

alert(jQuery(".warningmessage").size());

and

alert($("#" + warningId).size());

but both return 0. The only thing I can think of that might have an effect is that the content containing the element was loaded with Ajax, or maybe there's a syntax error on the page, although I can inspect it with Firebug and see the element there.

The page is part of an app so you have to log in to see it but I can post a demo login username/password if necessary.

The HTML is

<div class="warningmessage" id="rdvg2pgrktrbdw8um_warning"></div>
+2  A: 

You cannot find an element until after it's loaded, otherwise what are you finding?

For instance, you can do the call in your success method (this is an example, anywhere that runs after it's inserted into the DOM works), something like this:

$.ajax({
   // ...options...
   success: function(data) {
     //insert elements, including `#warningId`
     alert($("#warningId").size());
   }
});

If you're looking for a generic one, say any particular ajax call you might be bringing back a .warningmessage element, something like the .ajaxSuccess() method may be a better approach, like this:

$(document).ajaxSuccess(function() {
  $(".warningmessage").fadeIn();
});

If it's not a server-side warning and an actual error in the AJAX request itself you want to handle, check out the corresponding .ajaxError() event handler.

Nick Craver
+1  A: 

You have not provided enough details to receive a precise answer.

I would guess that your script is running before the page loads.
Move the <script> block to the bottom of the page.
Alternatively, wrap the code in $(function() { ... }).

SLaks
I don't think either of these work since it's it's loaded via AJAX, the element would still be loaded later than this runs.
Nick Craver
Sorry, I meant the content was originally loaded over Ajax, when the function containing the selection code is run, the content is definitely there - I can see it on screen. Selection is triggered by a keypress.
Oliver Kohll
It's this by the way:<div class="warningmessage" id="rdvg2pgrktrbdw8um_warning"></div>
Oliver Kohll
@Oliver - If `alert($(".warningmessage").size())` is 0, it's an ordering issue, did you try running it in the console?
Nick Craver
Is the `<div>` in question possibly loaded into an `<iframe>`, while the button and the code are *outside* the `<iframe>`?
Pointy
That could be it. The div is in an iframe, the javaScript that calls it is both in the <head> of that iframe content and in the enclosing page. I'll look into it...
Oliver Kohll
That was it. Thanks! Solved by getting the frame's document as a jQuery object and running .find(".warningmessage") on it.
Oliver Kohll