0

I am dynamically building out a page depending on what the user selects (ajax calls). The problem is that I am not able to apply any jquery to the markup that is returned. When I run get the page where I want it and run jQuery in the console I get [] returned to me.

How can I run jQuery against the returned markup?

Grady D
  • 1,889
  • 6
  • 30
  • 61

2 Answers2

1

You would have to append the markup to the DOM and then use JS or jQ to manipulate it (if that's what you want to do). That's why you're getting empty result set.

The mistake you might be making is trying to manipulate the DOM before it's ready... so whatever you do, do in the AJAX success callback.

It would be really helpful if you had shown some code. And you'd probably get better answers.

Shomz
  • 37,421
  • 4
  • 57
  • 85
1

Your problem is when you call the jQuery, if you call it on $(document).ready() you will run into trouble as on $(document).ready() you have not added the content. This is because JavaScript is asynchronous.

Here is a simple solution:

$.get('page-page-to-post.php').done(function(data) {
  // jQuery for dynamically called content
});

This way you add the content, and then you add jQuery functions. I ran into this problem a while back, I was thinking of JavaScript like CSS. CSS is constantly being called.

Another way you is to add a callback function. This is useful if you want to add actions to the dynamically added content from a separate script and it reduces code bloat.

// main.js
var myApp = {
  load: function(callback) {
    $.get('page-page-to-post.php').done(function(data) {
      callback();
    });
  }
}

Now, you can call this function like you would $(document).ready()

//new script
myApp.load(function() {
  // jQuery / JavaScript to attach to dynamically loaded content
});
Palmer
  • 173
  • 9