How do I access a dynamically generated element (or its values)?

4

I know that it is possible to use on() and delegate the selector, so it accesses the dynamic element from a static element, but if you can not use on() , what to do?

For example, within any function I need to get the id of a dynamically added element to change a style attribute and there is no event that triggers the on() :

jQuery

function(){
    if(1 + 1 == 2){
        //Não vejo como usar o on() nessa situação.
        $("#elemento").css("color", "black");
    }
    //Talvez...
    $("#elemento2").on((1 + 1 == 2), "#elemento", function(){
        $("#elemento").css("color", "black");
    });
}

Is there any other method, such as generating actions that are independent of other user actions or is it impossible to do this with jQuery?

    
asked by anonymous 10.07.2014 / 02:45

1 answer

4

It seems like you are confused about the need for delegation. When you select an element with jQuery - for example, with $('#algumId') -, the element is only selected if it exists. If it does not exist, you can not do anything with it (such as changing content, attributes, or associating a function that treats an event with that element).

Event delegation is a way to define how to handle events in a given element even before it exists in the DOM. However, by the time the event is triggered, the element naturally needs to already exist in the DOM for its delegated function to do something.

If you want to change the content or attribute of the element, simply do this directly:

function pintaDePreto(){
    $("#elemento").css("color", "black");
}

It does not make sense to speak in delegation in this case, there are no events involved. If the #elemento element exists when the function is called, color: black will be applied to it. If it does not exist, nothing happens. This does not have to do with whether or not the element is added dynamically, but with the very existence of the element in the DOM. If it does not exist, it does not make sense to want to change the color! So just make sure the function is called when the target element exists.

    
10.07.2014 / 20:44