Thursday, 15 March 2012

how to select different element id with the repeated matched class name using jquery

How to select element id when it have common style CSS class  name using jquery:

Scenario:

I have the repeated class name with different element id. on click or on mouse over, how could i get matched element id using jquery not by javascript. 

No need to do for each loop condtion

To achieve this, we need a pretty basic regular expression, like so.
The following example will not validate the html code. It just check the matched css class and get the respect whatevee attribute we want from that element.

Code:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="FindClassJQuery.aspx.cs" Inherits="MyWebApps.FindClassJQuery" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>

    <script src="js/jquery-1.6.4.min.js" type="text/javascript"></script>
    <script type="text/javascript">
    $(document).ready(function($) {
    $("[class^=testcss]").click(function(Event) {
    var id = $(this).attr('id');
    alert(id);
});
});
</script>
<style type="text/css">
.testcss1, .testcss2, .testcss3
{
color:Red;
font-weight:bold;
/*background-image:url(images/aa1.jpg);*/
}

</style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <div class="testcss1" id="div1">test1</div>
    <div class="testcss2" id="div2">test2</div>
    <div class="testcss3" id="div3">test3</div>
    </div>
    </form>
</body>
</html>