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
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.
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.
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.
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.
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.
Alternatively, add class="sales_info"
to your HTML mark-up.
Then, do this:
$(".sales_info").bind("click", function() { ... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With