Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind handler to multiple elements with similar IDs

Tags:

jquery

I have a lot of elements, the id attributes of them are something like element_num, where the num is the number of element. I want it so that when I click on one of these elements it gets deleted.

The first question is how to use a selector to find these elements (I think I need something like regex here).

The second question is how to obtain the clicked element id to delete it.

like image 657
Maki Avatar asked May 21 '11 14:05

Maki


People also ask

Can I have multiple elements with same ID?

The HTML id attribute is used to specify a unique id for an HTML element. You cannot have more than one element with the same id in an HTML document.

What happens if two HTML elements have the same ID?

If more than one element has been assigned the same ID, queries that use that ID will only select the first matched element in the DOM. This behavior should not be relied on, however; a document with more than one element using the same ID is invalid.

Can multiple HTML elements have the same class?

The HTML class attribute is used to specify a class for an HTML element. Multiple HTML elements can share the same class.


1 Answers

You can bind to all of them and delete them like:

$("[id*='element_num']").click(function() {
    // this.id is the id if you need it.
    $(this).remove();
});

The *= selector get's any element with an id containing the segment. Ideally you would wrap all these deletable items in a container so you can use DOM selection instead.

*=, .remove

like image 145
Raynos Avatar answered Oct 04 '22 03:10

Raynos