How to Call a Div With Specific Class in JQuery

JQuery was designed to make adding interaction to Web pages easier for designers. Given this fact, its method of "selecting" parts of the page is modeled after Cascading Style Sheets (CSS) selectors. This means that you can attach functions and events to parts of your Web pages using CSS-style selectors. When you want to call a div with a specific class name in jQuery, for example, you can use a combination of the tag selector and class name selector from CSS code. This code looks like "div .classname" and will get any div with the same class name, whether there is one or 10.

Instructions

    • 1

      Open your Web page in Notepad and add this code if you need to add jQuery to the page:

      <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>

    • 2

      Add "<script>" tags to your Web page code, placing them above "</head>" or above "</body>" depending on your preference. Inside the "<script>" tags, write a function to make the script wait until the page finishes loading:

      <script type="text/css">

      $(document).ready(function() {

      });

      </script>

      This will help prevent errors. All jQuery script code will go inside the curly braces of the "document ready" function.

    • 3

      Select your divs by class name using the same selection format as you would in a style sheet. For class names, this is the class name prefixed by a dot. When selecting in jQuery, however, place a dollar sign in front of a pair of parantheses and place the selector inside quotes within the parantheses:

      $(".classname");

      To select only divs that share the same class name, write "div" in front of the class selector:

      $("div .classname");

    • 4

      Attach a jQuery function to the selector:

      $("div .classname).click();

      The "click()" function adds a "click" event to the selector, telling the script to do something when the user clicks on a div of a particular class. Open a new function inside "click()" -- or whichever function you want to use -- to write the "something" that happens on the event:

      $("div .classname).click(function() {

      // Write code here to do something when the user clicks on the div or divs

      });

Related Searches:

References

Resources

Comments

Related Ads

Featured