Javascript - Removing Element By Part Of Id
Solution 1:
Here is how you can do this with pure JavaScript without any libraries:
var divs = document.getElementsByTagName('div'),
forEach = Array.prototype.forEach,
regex = /^foo.*$/;
forEach.call(divs, function (d) {
if (d.id !== undefined && regex.test(d.id)) {
d.parentNode.removeChild(d);
}
});
In the example above all div elements which ids start with foo
will be removed.
Here is an example: http://jsfiddle.net/UemQ5/
Solution 2:
You don't have to use a regex, you can use one of these 3 selectors, depending on what you need: starts with, ends with, or contains.
Starts with: $("[id^=item]")
Ends with: $("[id$=item]")
Contains: $("[id*=item]")
Or if they don't suit your needs, there's even more here: http://api.jquery.com/category/selectors/
Solution 3:
you can use jquery selector regex to resolve it :)
read this : http://james.padolsey.com/javascript/regex-selector-for-jquery/
Solution 4:
1.jQuery Attribute Starts With Selector
On jQuery, "Attribute Starts With Selector" selects elements that have the specified attribute with a value beginning exactly with a given string.
jQuery('[attribute^="value"]')
If you want to remove the divs which 'id' starts with "ABC_", your code goes something like this:
$('div[id^="ABC_"]').remove();
The document is here http://api.jquery.com/attribute-starts-with-selector/
2. jQuery Attribute Ends With Selector
Similarly,"Attribute Ends With Selector" selects elements that have the specified attribute with a value ending exactly with a given string.
jQuery('[attribute$="value"]')
If you want to remove the divs which 'id' ends with "_ABC", your code goes something like this:
$('div[id$="_ABC"]').remove();
The document is here http://api.jquery.com/attribute-ends-with-selector/
3. jQuery Attribute Contains Selector
Lastly,"Attribute Contains Selector" Selects elements that have the specified attribute with a value containing the a given substring.
jQuery('[attribute*="value"]')
If you want to remove the divs which 'id' contains "ABC", your code goes something like this:
$('div[id*="ABC"]').remove();
The document is here http://api.jquery.com/attribute-contains-selector/
Post a Comment for "Javascript - Removing Element By Part Of Id"