0

Let's say I have a button on a page, if clicked it adds a div popup.

How can I access the div's content through JavaScript? Is this possible? I've tried searching the page with jQuery selectors but I did not find the div popup.

I have a bookmarklet that is similar to what follows:

javascript:(function() {
    alert($('newDivId').val());
})();

...suppose that newDivId is the id of the newly created div, if I execute that code by clicking on the bookmarklet I get an error saying that val() cannot be invoked on a null object.

I do not have access to the page source; do you have any suggestion?

4
  • I think you may need to include some code for better clarification of what you're trying to do... With jQuery, to access a div's contents you would usually just use $("#somediv").contents(); so perhaps explain why you can't in this situation... Commented May 15, 2011 at 21:34
  • The created div is not present if I don't click on the button, so I think that the problem is related to this fact. Commented May 15, 2011 at 21:38
  • You definitely can't get the content before it's created! See my suggestion below. Commented May 15, 2011 at 22:15
  • @Jed: Once the div is created I click on the bookmarklet to execute the code that looks for the id. I know the content is created because I see it on the page. Commented May 15, 2011 at 22:19

1 Answer 1

1
$('#id_of_div').html()

OR

$('.class_of_div').html()

OR

$('#id_of_div_parent div').html()

ETC.

If that doesn't work, you might be trying to select it before it has been full inserted into the DOM. Be sure it's fully loaded before you try to access it.

Sign up to request clarification or add additional context in comments.

7 Comments

I've already tried this of course. I think this does not work because the div is loaded dinamically after the button is clicked.
Since we can't see the code, and how the function(s) is being called exactly, it's sort of hard to lend an eye to this one without knowing more...
Assuming you've fixed your code above to the proper syntax...If you don't have access to the function that loads the content, you can create your own callback using setTimeout, checking for the div via id, clearing the timeout and moving on once it's there.
@Jed: I haven't fixed it since I don't know what's wrong in that line. @Jordan Rynard: Assume that you have a div in the page that is loaded dinamically by a script after a click, how to you acces its content?
See my examples. It needs to be $('#div_id').html(), not $('div_id').val()
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.