How can I select an element by id and class in javascript? - 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);

Related

jQuery child elements with same ID

Imagine that I have this HTML structure:
<div id="bodyRead">
...
<div id="List"></div>
</div>
...
<div id="bodyWrite">
...
<div id="List"></div>
</div>
As you can see, I have the #List inside two different divs (bodyRead and bodyWrite). For a lighter code, I preferred to work with id instead of class (even knowing that duplicate IDs isn't valid, the code makes more sense to me), and selecting the #List on jQuery like this:
$('#bodyRead #List').off('click').on('click', function() ...
$('#bodyWrite #List').off('click').on('click', function() ...
works. I'm always taking care of make duplicate IDs only on child divs, where I can separate them by their parent div on jQuery selector.
Is this approach very wrong? I mean, this can get me in trouble?
don't duplicate your Id even in child element .. change it to class="List"
then you can use
$('.List').on('click',function(){
var getparent = $(this).parent().attr('id');
alert(getparent);
});
and if class="List" not first level child of any of #bodyRead or #bodyWrite
add class to it
<div id="bodyRead" class="mainDiv">
<div id="bodyWrite" class="mainDiv">
and then use
$('.List').on('click',function(){
var getclosest = $(this).closest('.mainDiv').attr('id');
alert(getclosest);
});
You should expect that CSS and JavaScript (including jQuery and other frameworks) behave in accordance with the HTML specifications. ID must be unique, multiple instances of the same ID is not supported. See below:
From HTML 4.01 spec:
id = name [CS] This attribute assigns a name to an element. This name
must be unique in a document.
class = cdata-list [CS] This attribute
assigns a class name or set of class names to an element. Any number
of elements may be assigned the same class name or names. Multiple
class names must be separated by white space characters.
http://www.w3.org/TR/html401/struct/global.html#h-7.5.2
This is from the HTML 5 spec:
3.2.5.1 The id attribute
The id attribute specifies its element's unique identifier (ID). [DOM]
The value must be unique amongst all the IDs in the element's home
subtree and must contain at least one character. The value must not
contain any space characters.
There are no other restrictions on what form an ID can take; in
particular, IDs can consist of just digits, start with a digit, start
with an underscore, consist of just punctuation, etc.
An element's unique identifier can be used for a variety of purposes,
most notably as a way to link to specific parts of a document using
fragment identifiers, as a way to target an element when scripting,
and as a way to style a specific element from CSS.
Identifiers are opaque strings. Particular meanings should not be
derived from the value of the id attribute.
Well i feel this is a bad approach because the browser creates the DOM(document object model) for the page, which takes into consideration that each Id has a unique value.It would be hard to play with the duplicate Id's in javascript when you want to manipulate you need to consider parent as well as child id each time. So its better to use classes instead.
Although id selectors are meant to be unique your code will work as long as you make sure to use correct nesting. In other words #bodyRead #List and #bodyWrite #List are perfectly fine as long as you don't create ambiguity by leaving out the parent selectors to #List.
Still, using multiple identical ids on the same page is just asking for trouble. You should reconsider switching to class selectors or reevaluate if it is really worth the potential trouble of sticking with your original idea.
You certainly should not use duplicate id's in an html page. If you have a similar concept within two different div's then class makes more sense anyway. So change the List ids to classes and then you can access them like this:
$('#bodyRead .List').off('click').on('click', function() ...
$('#bodyWrite .List').off('click').on('click', function() ...
Even if your code works now due to how jQuery works, because the html specifications say not to do this, you can not know for certain that your code will continue to work in the future.

Select elements jQuery with Regex

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']")

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');

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

Help me with my selector, the ID is dynamically changing every page load

I want to scan a website using jQuery, but the ID is constantly changing, but there's a permanent pattern for the ID that I'm searching for:
app7019261521_the_coinb4678bc2
app7019261521_the_coind42fgr23
app7019261521_the_coing0992gvb
app7019261521_the_coin12e5d0aa
The IDs always starts with app7019261521_the_coin
But my problem is I don't know how to put that in jQuery selector.
$("#app7019261521_the_coin")
Doesn't seem to work
So how can I make this work?
$("[id^=app7019261521_the_coin]")
Should work - but its MUCH slower selector than knowing the real ID - or assigning a class. This selector will scan every element on the page one at a time, there is no good way for this selector to be optimizied. 9 times out of 10 though you could build a better selector: Is this #app7019... element the direct child of another element that is easier to determine? like a id='container'?
$("#conainter > [id^=app7019261521_the_coin]"); for instance
From the jQuery Selector Documentation
[attribute^=value] Returns: Array<Element(s)>
Matches elements that have the specified attribute and it starts
with a certain value.
can you set a class and just call it by a class name?
you may also be able to try
$("div[id^=app7019261521_the_coin]")
This will find all div's that start with app7019261521_the_coin
Replace div with whatever element type you are searching for.
$j('div[id^=app7019261521_the_coin]')
Remember this is not very optimal, as it causes the script to check the id attribute of every matched element.
You might want to see how you can add a class to the element or at least find the parent element first and traverse from there.

Categories