Vicky
Vicky

Reputation: 257

How can I get id of span and make it display none which is dynamically generated?

I have created span tags dynamically and appended to div. Now I want to get its id, the one I select and delete it. It is something like jquery tagit. Below I am using this but it is not working. See the id can get when I click a particular span.

$('span').on('click', function (e){
alert(e.target.Id);
});

Upvotes: 1

Views: 70

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074495

You don't need an id (and the span may well not have one), you already have a reference to the element: this. That's standard jQuery behavior. (In fact, it's standard across the various ways you can hook up events without jQuery too.)

So

$('span').on('click', function() {
    $(this).remove(); // Removes the one that was clicked
});

(Or, yes, add the e back and use e.target: $(e.target).remove();)


Re your comment:

I tried using that code by giving alert also but the click event is not firing.

That suggests that the spans in question don't exist as of when your code runs, and so you don't end up hooking their click event.

To deal with that, you probably want to do a delegated handler: In dev tools, right-click one of these spans and find a common ancestor that they have that does exist as of when your code runs. (In the worst case, that could be document, but usually it's better to scope things more tightly.) Then:

$('selector-for-that-ancestor-element').on('click', 'span', function() {
    $(this).remove(); // Removes the one that was clicked
});

See on for details. Also, if the spans have any identifying characteristics (like a class or some attribute), you might want to include that in the delegation selector above to be more specific.

Upvotes: 3

Related Questions