简体   繁体   中英

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 #xy , 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

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

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:

  1. 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

  2. You can also limit by parent type: div .ui-slider-handle

  3. Or only direct children: div > .ui-slider-handle

See jQuery selectors for all the goodies .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM