Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using jQuery to delete all elements with a given id

I have a form with several spans with id="myid". I'd like to be able to remove all elements with this id from the DOM, and I think jQuery is the best way to do it. I figured out how to use the $.remove() method to remove one instance of this id, by simply doing:

$('#myid').remove() 

but of course that only removes the first instance of myid. How do I iterate over ALL instances of myid and remove them all? I thought the jQuery $.each() method might be the way, but I can't figure out the syntax to iterate over all instances of myid and remove them all.

If there's a clean way to do this with regular JS (not using jQuery) I'm open to that too. Maybe the problem is that id's are supposed to be unique (i.e. you're not supposed to have multiple elements with id="myid")?

like image 359
Chris Avatar asked Nov 19 '10 08:11

Chris


People also ask

How do I select all elements with ID?

The id selector uses the id attribute of an HTML element to select a specific element. The id of an element is unique within a page, so the id selector is used to select one unique element! To select an element with a specific id, write a hash (#) character, followed by the id of the element.

What is the correct jQuery code to hide all elements with ID?

jQuery hide() Method The hide() method hides the selected elements. Tip: This is similar to the CSS property display:none. Note: Hidden elements will not be displayed at all (no longer affects the layout of the page). Tip: To show hidden elements, look at the show() method.

What jQuery method is used to completely remove attributes from elements?

To remove all attributes of elements, we use removeAttributeNode() method.

How do I select multiple elements by ID?

Use the querySelectorAll() method to select elements by multiple ids, e.g. document. querySelectorAll('#box1, #box2, #box3') . The method takes a string containing one or more selectors as a parameter and returns a collection of the matching elements.


2 Answers

.remove() should remove all of them. I think the problem is that you're using an ID. There's only supposed to be one HTML element with a particular ID on the page, so jQuery is optimizing and not searching for them all. Use a class instead.

like image 150
mpen Avatar answered Sep 19 '22 23:09

mpen


All your elements should have a unique IDs, so there should not be more than one element with #myid

An "id" is a unique identifier. Each time this attribute is used in a document it must have a different value. If you are using this attribute as a hook for style sheets it may be more appropriate to use classes (which group elements) than id (which are used to identify exactly one element).

Neverthless, try this:

$("span[id=myid]").remove(); 
like image 45
ace Avatar answered Sep 23 '22 23:09

ace