Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery match only part of id from div

Tags:

jquery

I ran into an unusual situation yesterday night.

I need to match only part of id. Let me clear you all with an example

I have few divs like

<div id="sales_info_1">... ...... ...... ...... ...</div> <div id="sales_info_2">... ...... ...... ...... ...</div> <div id="sales_info_3">... ...... ...... ...... ...</div> 

and jQuery goes like

jQuery("div#dont_know_what_to_write_here").bind("click", function(){     ... ...... ...... ...... ... }); 

I need to match only sales_info, ignoring _1, _2 or _anything, can anyone suggest me how to achieve this?

Thanks

like image 881
I-M-JM Avatar asked Jan 20 '11 05:01

I-M-JM


People also ask

How to use id selector in jQuery?

In jQuery, the class and ID selectors are the same as in CSS. If you want to select elements with a certain class, use a dot ( . ) and the class name. If you want to select elements with a certain ID, use the hash symbol ( # ) and the ID name.

How will you select only the odd anchor tags on the page?

To achieve the best performance when using :odd to select elements, first select the elements using a pure CSS selector, then use . filter(":odd") . Selected elements are in the order of their appearance in the document.

How check ID is present or not in jQuery?

In jQuery, you can use the . length property to check if an element exists. if the element exists, the length property will return the total number of the matched elements. To check if an element which has an id of “div1” exists.

How do I know which ID is clicked in jQuery?

Answer: Use the jQuery attr() Method You can simply use the jQuery attr() method to get or set the ID attribute value of an element. The following example will display the ID of the DIV element in an alert box on button click.


2 Answers

You could use the "Starts With" selector:

$('div[id^="sales_info_"]') 

I'd rather recommend you use a unique class name for your elements that you can select on though.

like image 71
deceze Avatar answered Sep 20 '22 17:09

deceze


Alternatively, add class="sales_info" to your HTML mark-up.

Then, do this:

$(".sales_info").bind("click", function() {    ... } 
like image 21
Chuck Callebs Avatar answered Sep 24 '22 17:09

Chuck Callebs