Polar
Polar

Reputation: 3537

How to set attribute to element that is dynamically created?

I'm getting response from a $.post and it contains elements. The element contains <a> and <img>.

I want to prevent the <a> element from doing it's default functions when it is clicked and I want to disabled the draggable option for both the element <a> and <img>.

Using .on() you can define your function once, and it will execute for any dynamically added elements.

E.g: These will prevent anchor element from doing it's default function when it is clicked.
$('body').on('click', 'a', function (e) { "use strict"; e.preventDefault(); });

How about setting the attribute for it? The below code doesn't work for dynamic element. $('a').attr('draggable', false);
$('img').attr('draggable', false);

Upvotes: 0

Views: 825

Answers (1)

Polar
Polar

Reputation: 3537

Assuming you are adding that response element somewhere into your markup.

The Markup

<div id="container">
    <!--Add dynamic element here-->
</div> 

The JS

$('body').on('click', 'a', function (e) {
   "use strict";
   e.preventDefault();
});

$.ajax({
    type: "POST",
    url: ServerAddress,
    success: function (data) {
        $('#container').html(data); //1: Insert the element into your markup
        $('#container a').attr('draggable', false); //2: The element is ready to add some attribute
        $('#container img').attr('draggable', false); //2: The element is ready to add some attribute
    }
});

You just need to wait until it's parsed into an object.

Upvotes: 2

Related Questions