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")?
.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.
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();
id of DOM element shout be unique. Use class instead (<span class='myclass'>).
To remove all span with this class:
$('.myclass').remove()
if you want to remove all elements with matching ID parts, for example:
<span id='myID_123'>
<span id='myID_456'>
<span id='myID_789'>
try this:
$("span[id*=myID]").remove();
don't forget the '*' - this will remove them all at once - cheers
Working Demo
The cleanest way to do it is by using html5 selectors api, specifically querySelectorAll().
var contentToRemove = document.querySelectorAll("#myid");
$(contentToRemove).remove();
The querySelectorAll() function returns an array of dom elements matching a specific id. Once you have assigned the returned array to a var, then you can pass it as an argument to jquery remove().
You should be using a class for multiple elements as an id is meant to be only a single element. To answer your question on the .each() syntax though, this is what it would look like:
$('#myID').each(function() {
$(this).remove();
});
Official jQuery documentation here.
As already said, only one element can have a specific ID. Use classes instead. Here is jQuery-free version to remove the nodes:
var form = document.getElementById('your-form-id');
var spans = form.getElementsByTagName('span');
for(var i = spans.length; i--;) {
var span = spans[i];
if(span.className.match(/\btheclass\b/)) {
span.parentNode.removeChild(span);
}
}
getElementsByTagName is the most cross-browser-compatible method that can be used here. getElementsByClassName would be much better, but is not supported by Internet Explorer <= IE 8.
Working Demo
Related
I'm trying to get the IDs of SVG elements except for a specific one being passed to the highlight() function by combining the children() method with the not() method singling out the specific ID.
var allOthers = $(".container").children().not(elem);
I want to affect all other elements' opacity. I tried this way of singling out a specific element ID out of a whole array of them before on some other pr0ject, but I don't know why it says that allOthers is undefined. Am I doing something wrong here?
I made a fiddle.
It is not allOthers which is undefined, it is allOthers.style. You are using vanilla js when you meant to use jQuery, change...
allOthers.style.opacity = "0.1";
for:
allOthers.css("opacity", "0.1");
Noob Question on Data Attribute
I was wondering will using data-attribute in jQuery Selector can bring any trouble in the future?
I'm trying to reduced the usage of .class and #id as jQuery Selector, since most of data I'm working on will generated from data-attribute
example of the code
$(document).ready(function(){
var mydata = $(document).data('my-data-attribute');
});
will the code above slowing the load time?
or
$('[data-suffix-attribute="some_value"]').each(function(){
......
});
or
$('[data-suffix-attribute="delete"]').click(function(){
// delete action happening here
});
will this bring trouble?
$(document).ready(function(){
var mydata = $(document).data('my-data-attribute');
});
The code above will not work. If you want to read the HTML5 data attribute of an element using the jQuery .data() method firstly you need to select the relevant element using a jQuery selector and then you can use the method as is shown below:
var mydata = $('.example').data('suffix');
This will read the value of the data-suffix attribute of an element with a class of "example".
The other important thing to note when using the .data() method is that you have to omit the data- prefix from the selector to read the value stored in that attribute.
The way you have selected the attribute before the .each() method will work:
$('[data-suffix-attribute="some_value"]');
However, it would be better if you can narrow it down to a specific element like:
$('div[data-suffix-attribute="some_value"]');
This is because the first selector will go through every node in the document which will take more time whereas the second will only go through the div tags in the document.
The attribute selector is supported by the native query selectors so it is fine. As far as future is concerned I don't think in near future it will be a problem.
But it will be better if you can use a element selector attached to the attribute selector like $('div[data-suffix-attribute="delete"]')
If you are very worried about performance it will be a better choice to add a class attribute to the desired elements and then use class selector
It would be better to use id in selector which is fast obviously,
If you have multiple data attributes then it is better to use $('[data-suffix-attribute="delete"]').click();.
Instead of this you can use the parent selector for your data-attribute elements like,
$('#parentId').on('click','[data-suffix-attribute="delete"]',function(){
// delete action happening here
});
#parentId contains all data attribute elements
I have problem with filter more identic id in the same page.
document.getElementById(val1).innerHTML=xmlhttp.responseText;
I have three the same <div id="name"></div> on one page. And only first div display content. I try with jQuery and filter... but I dont have progress.
The id selector is something to return one unique element (or none if not found). That's why you shouldn't use multiple ids - it will always return [at most] only one (the first).
Fix that fault by using classes or something.
If you really have to get multiple elements with the same id, you can do by using an attribute selector:
$('[id="name"]').html(xmlhttp.responseText);
// or
[].forEach(document.querySelectorAll('[id="name"]'), function(el) {
el.innerHTML = xmlhttp.responseText;
});
document.getElementById
return only first element that having the specified ID. Id should always be unique.
You can try with other attributes like class and then use
document.getElementsByClassName("myClass")
that will return all the elements of given class.
ids should be unique. You shouldn't have two or more elements on the same page with the same id. You can use class names to identify them, and those can definitely be the same. I don't know your code, but try using document.getElementsByClassName (not supported in IE8), or using jQuery to simplify what you are trying to do: $('.my_class_name').html(xmlhttp.responseText)
I just wanted a fast/easy/simple way to check for existing ID on a specific element (div in this case)..
Can't seem to find code sample for this..im using jquery but i dont think i need to do jquery on this one, just basic getElement.. but i need to isolate the search inside a div block.. because the id does exist in other elements on the page but i need to know if it exist in a specific area/div.
so instead of just
document.getElementById(target_id);
i need something like:
divName.getElementById(target_id);
or
$("document.divName").getElementById(target_id);
or
$(".divName").document.getElementById(target_id);
Can't seem to find something that works.
IDs are supposed to be unique and no two elements in page should have same id. You may search some element with some class in div with specific ID.
$('#divId .someClass')
or using find()
$('#divId').find('.someClass')
or using context, jQuery( selector [, context ] )
$('.someClass', $('#divId'))
var mySubDiv = myParentDiv.querySelector("#mySubDivId")
is equivalent to
var mySubDiv = document.querySelector("#myParentDivId #mySubDivId");
// don't forget the space : #myParentDiv#mySubDivId won't work
where querySelector and querySelectorAll are very useful functions, enough for me to avoid using jQuery : they accept any css selector
in real life, using the same Id for different DOM elements often happens.
id's should be unique, you can check for element using:
$(".your_parent_div").find("div#some_unique_id");
you can use it for the getElementsByTagName or ClassName, but ID is unique over document. so doesn't need to do that. better to use a special ID.
and in every id define as a element in javascript and you can just write id's name and use it, like this :
ID.style.color = red;
According to my understanding on your question, You have used two id's with same name when u execute, It takes only first ID so you are asking to take id from the specific div, well that is bad type of coding to use two id for same name instead go for class if want to use same name.
solution for your question is -this ->
var someDiv = document.getElementsByClassName("divName");
var someId = someDiv[0].getElementById("target_id");
I'm a guy used to mootools' way of chaining selectors, and I can't seem to find anywhere how to do the same in jQuery.
Suppose I have a select element in the selectObj variable. What I need is to get the last option in that select.
In mootools I would have done something like:
var option = $(selectObj).getElement('nth-child(last)')
Can I do something similar, or what is the way of getting that last option in jQuery?
PS. I know about the parent > child selector, but I can't really use it because I don't know what selector has been used to get the select. I only have the resulting element.
$(selectObj).find(':last')
You can use find to perform another query within the current query.
In general, you can check out the Selectors and Traversal pages on jQuery docs when you're trying to figure out how to select something.
var option = $(selectObj).children(":last");
will return the last child of any element
You can also use .last() for this purpose.
jQuery has the :last Selector
$("tr:last").stuff()
Will do stuff to the last row in a table.