ReynierPM
ReynierPM

Reputation: 18660

How do I let the DOM know about new elements created on the fly?

I am making an AJAX call and I am building some HTML on the backend side. I am returning them as a JSON and then using jQuery I render them, something like:

$(data.message).each(function (index, value) {
    $('#states_table tbody').append('<td>' + value.edit_link + '</td>');
});

value.edit_link contains the following HTML:

<a id="edit_0" 
   title="Edit" 
   onclick="javascript:return false;" 
   class="edit"
>Edit</a>

Then I will end up with something like this:

enter image description here

And as you can see the link doesn't have the hand cursor. My guess is that the DOM doesn't know about them when the page is rendered for first time so no CSS properties or default properties will be applied which makes me ask:

In order to have the links with the cursor: hand, how do I let the DOM know about this new elements?

Upvotes: 1

Views: 63

Answers (1)

paolobasso
paolobasso

Reputation: 2018

Solution 1

Add to your link html href="#" or href="javascript:void(0)" so:

<a href="#"
   id="edit_0" 
   title="Edit" 
   onclick="javascript:return false;" 
   class="edit"
>Edit</a>

For a full comprehension of <a> html tag read this.

If you don't know if is better href="#" or href="javascript:void(0)" (nobody knows) read this discussion.

Solution 2

Don't use an <a> but a <button> following the sentiment:

if <a> button doesn’t have a meaningful href, it’s a <button>

(for someone a <button> outside a <form> feels wrong. You decide.)

so:

<button id="edit_0" 
   onclick="javascript:return false;" 
   class="edit"
>Edit</button>

Button reference there.

Upvotes: 6

Related Questions