Select elements jQuery with Regex - javascript

I have a HTML page where many elements are dynamically inserted as the user requests. Each of these elements have an id attribute with some string plus a numeric id value plus another string.
Example: budget_budget_alive_elements_attributes_10_unit_value
And so I tried the following selector:
$("#budget_budget_alive_elements_attributes_\d+_unit_value");
But it unfortunately does not work.
Some person wrote an article of an extension to jQuery selector for fetching these kinds of ids but I had no luck with that, either.
Can you help me here? Given the constraints of the element's id values, how can I make a selector for them?

You'd better use class selector (by adding same class to these elements).
Else you have to use something like:
$("[id^='idbudget_budget_alive_elements_attributes']")

Related

Why does the jquery selector ("id,id") selects all elements with duplicate IDs

I came across some year old code written by a good developer (yes, I knew him personally) to access all elements having the same id.
$("#choice,#choice")
It returns all elements having the id. But if we use the below
$("#choice")
It returns only the first match, as expected.
After searching for some time, I'm unable to figure out any official links pointing to his technique, as to how it selected all elements with duplicate id.
Can anyone please explain how is this working ?
UPDATE
Please see the question is not about what alternative to use. I'm aware of classSelectors and attributeSelectors and know having duplicate IDs is not recommended, but sometimes you just have to live with years old code the way it is (if you know what I mean).
http://jsbin.com/zodeyexigo/1/edit?html,js,output
If you look at the code of sizzle.js that jQuery uses for selecting elements based on selector you will understand why this happens. It uses following regex to match simple ID, TAG or class selector:
// Easily-parseable/retrievable ID or TAG or CLASS selectors
rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,
but as the selector in question is $("#ID,#ID") it does not match with the selector and uses querySelectorAll (line no 270 in ref link), which replaces selector to "[id='" + nid + "'] " (line no 297 in ref link) which selects all the elements with matching ID.
However, I agree with the other people in this thread, that it is not good idea to have same ID for multiple elements.
Having 2 elements with the same ID is not valid html according to the W3C specification.
When your CSS selector only has an ID selector (and is not used on a specific context), jQuery uses the native document.getElementById method, which returns only the first element with that ID.
However, in the other two instances, jQuery relies on the Sizzle selector engine (or querySelectorAll, if available), which apparently selects both elements. Results may vary on a per browser basis.
However, you should never have two elements on the same page with the same ID. If you need it for your CSS, use a class instead.
If you absolutely must select by duplicate ID, use an attribute selector:
$('[id="a"]');
Take a look at the fiddle: http://jsfiddle.net/P2j3f/2/
Note: if possible, you should qualify that selector with a tag selector, like this:
$('span[id="a"]');
Having duplicated id on the page making your html not valid . ID is unique identifier for one element on the page (spec). Using classes, that are classify similar elements that's your case and $('.choice') will return set of elements
So in JS Fiddle i have shown an example of what jQuery is doing.
https://jsfiddle.net/akp3a7La/
When you have a
$('#choice,#choice');
It is actually getting all the instances of the objects #choice twice, and then filtering out any duplicates.
in my example i show you how it does that also when you have something like this
$("#choice,li");
Where items are actually your #choice items.
In the Jquery Documentation
https://api.jquery.com/multiple-selector/
it talks about multiple Selectors, which is what i think is happening here, your developer friend is selecting the same ID twice, and it would be returning it twice. as you can only have one input with the same ID once on a page (good html syntax)

Call element by id in javascript

I have a repeater and have a label with an icon inside it.
<strong><i id="iconProperties" class="icon-caret-right"></i> Properties</strong>
When i click a button the icon-caret-right must be turned to icon-caret-down. i have written the code as follows:
$('#iconProperties').removeClass('icon-caret-right').addClass('icon-caret-down');
When i use this code only the first row of the repeater is working. all other rows's icons are not changing. What is the mistake?
ASP.net generates unique ids for html elements and only one element can have id iconProperties that you used in selector. You can use Attribute Contains Selector [name*="value"] instead of id selector to get all the matching elements.
$('[id*=iconProperties]').removeClass('icon-caret-right').addClass('icon-caret-down');
If your ids have a similar name, you're probably after something like
$('[id^=iconProperties]').removeClass('icon-caret-right').addClass('icon-caret-down');
Which will update all items beginning with id "iconProperties".
It might be worth noting that it is common practice to use unique ids.
Try this:
$('#iconProperties').find('.icon-caret-right').replaceWith('.icon-caret-down');

Ajax, filter div by id.

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)

How can I select an element by id and class in javascript?

I want to know if we can select an element by using its id and class at the same time. I know in css we can do that with #x.y, but but how can it be accomplished in javascript? I tried the following code and it worked fine but then all the controls with ui-slider-handle class got affected(which is obvious). I think I need a combination of id and class both so that only that particular element will be affected.
Javascript:
$(".ui-slider-handle").text(ui.value);
A combination of ID and class for selecting elements is useless as IDs are meant to be unique.
never have multiple identifiers with the same value in one page!
If you want multiple elements with the same attributes, use a class. If not, consider an ID or a class.
If you want to have a lot of elements with the same attributes, but one with extra attributes, you can give that one an ID and assign extra attributes to the ID
You will never need to do this since the ID is unique; if you know it, you can already identify the element.
Your problem is actually that your selector matches too many elements. There are other ways to limit the "range" of a selector:
Add a parent element with a certain ID/class: .parent .ui-slider-handle matches only elements with the class ui-slider-handle that are children of all elements with the class parent
You can also limit by parent type: div .ui-slider-handle
Or only direct children: div > .ui-slider-handle
See jQuery selectors for all the goodies.
Since ids should be unique, you should be able to do your selector by only id. If are wanting to apply the same attribute to multiple elements, then you should use a class. In your scenario it seems you should be fine with just using id like this:
$("#id").text(ui.value);
What you can write is:
$("#ID.ui-slider-handle").text(ui.value);
The string inside the quotes is a normal CSS selector, which supports both classes and ids. However, the above code is redundant and slow, and unless you want to select that particular id only if it has a certain class, it would be preferable to write:
$("#ID").text(ui.value);

Jquery doesn't apply hide() to all of the divs with the same ID

I'm making a site, and the html is displayed through php with data fetched from a database.
I have a foreach() function, so all of the things displayed have the same DIV ID's.
It ends up being like 4 DIVs with the same ID (#content), so the PHP works fine, but I have a jQuery script and when I call the jQuery("#content").hide(); it only hides ONE of the DIV's not all of them, and I want it to hide all of them. Is there something else I have to do?
Thanks.
You should use a class (.class_name), not an id--only one DOM element may have a given ID, otherwise it's invalid HTML. It's reasonable for an ID selector to return only a single element.
IDs on elements on a page should be unique. So every HTML tag you specify should have a different ID. If you want to hide all of a certain element, it might be suitable to add a class to the elements you wish to hide?
e.g.
<div class="divToHide">Content...</div>
<div class="divToHide">Content...</div>
<div class="divToHide">Content...</div>
Then your jquery would be:
$(".divToHide").hide();
That's simply because you cannot have more than one element with a specified ID. IDs are and must be unique. Only one single element with the same element may exist in a DOM.
Failing to follow this rule may result in broken scripts and other horrors.
You can use classes for this purpose.
an ID can only be used ONCE in HTML! because its a id and a id should always be Unique

Categories