jQuery - Find dynamically created element without events

474
November 22, 2016, at 11:21 AM

Tho this question has been asked before, and the answer is this:

$('#container').on('click','#dynamicElement', function(){ /* the code */ });

The code above will find the #dynamicElement when its being clicked on. But what if there is no click, nor any other event?

Suppose the following scenario:

$.ajax(
    url:'file.php',
    data: {'param':'value'},
    success: function(response){
         /*
         how would I get #dynamicElement if it was not click on?
         the element had no event fired at all, nor had any of its parennt
         containers.
          Now what?
         */
    }
);
Answer 1

If your new element is being added to the page inside the success callback, at that point you can call $('#dynamicElement')

Using $('#dynamicElement') anywhere outside of the callback would not return the element since it had not been added to the DOM yet.

Answer 2

How event binding works is as long as that element is in the DOM itself, you can access it by

$('#dynamicElement)

The reason you need event delegation is when you dynamically create the elements after you bound the event. Then, when the event is fired, it looks through all the children of the element you bound it to to find if there are any elements matching your selector.

However, if you know that the element has already been appended to the DOM, you can bind it directly without event delegation, and access it through finding it by ID.

If it hasn't yet, there is no way for you to manipulate it as it doesn't exist yet.

Rent Charter Buses Company
READ ALSO
dynamic form fields with javascript, php & mysql: strange error

dynamic form fields with javascript, php & mysql: strange error

I get an really strange error with my dynamic form field script. It is not so easy to explain, but I will do my best.

267
Element value not showing up in console when set via jQuery

Element value not showing up in console when set via jQuery

I am slightly confused about this. .

341
jQuery's toggle class requires two clicks in Internet Explorer?

jQuery's toggle class requires two clicks in Internet Explorer?

Works great in Firefox / Chrome / Microsoft Edge, but when the button is clicked in the latest Internet Explorer 11, it takes two clicks to toggle class when it should only take one. Everything else performs as it should (it plays and stops the music when it should)....

367
Toggle (or slide) out specific div on click and hide others

Toggle (or slide) out specific div on click and hide others

I've been browsing all day trying to find and answer to my problem. I'm stumped now and been running into walls.

329