Skip to content
jQuery Selectors — Complete Guide to Targeting DOM Elements

jQuery Selectors — Complete Guide to Targeting DOM Elements

DodaTech Updated Jun 6, 2026 9 min read

jQuery selectors let you find and target DOM elements using CSS-style syntax plus jQuery-specific extensions, forming the foundation of every jQuery operation you’ll ever write.

What You’ll Learn

  • How basic CSS selectors work in jQuery (ID, class, element, combinators)
  • Attribute selectors for targeting elements by attributes
  • jQuery extension selectors like :first, :eq, :has
  • Form selectors for input elements and states
  • Custom selectors and performance optimization
  • Common selector mistakes and how to avoid them

Why jQuery Selectors Matter

Selectors are the gateway to every jQuery operation. You can’t manipulate, animate, or attach events to elements you can’t find. Think of selectors as fishing lines — you cast the right one, and you catch exactly the element you need. In DodaTech’s Durga Antivirus Pro UI, selectors pinpoint specific threat entries, toggle visibility on alert panels, and filter search results in the dashboard. Mastering selectors means you can surgically target any element on any page.

Selector Learning Path

    flowchart LR
  A[jQuery Basics] --> B[jQuery Selectors: You Are Here]
  B --> C[CSS Selectors]
  B --> D[Attribute Selectors]
  B --> E[jQuery Extensions]
  B --> F[Form Selectors]
  C --> G[Events & DOM Manipulation]
  
🎯
Prerequisites: HTML element structure and attributes, CSS selector syntax (classes, IDs, combinators), and https://tutorials.dodatech.com/frameworks/jquery/jquery-basics/.

How Selectors Work in jQuery

Every jQuery statement starts with $(selector). The selector is a string that tells jQuery which elements to find. jQuery uses the browser’s native querySelectorAll under the hood for CSS selectors, plus its own engine for jQuery-specific extensions.

Think of selectors like a postal address. #main is like “123 Main Street” (specific, one building). .article is like “every house on Elm Street” (multiple matches). div p is like “every mailbox in every building on Elm Street” (nested).

Basic CSS Selectors

These work exactly like they do in CSS stylesheets:

// Let's break down each one:

$("*")            // ALL elements — like saying "everything in the room"
$("#myId")        // By ID — the fastest selector, maps to getElementById()
$(".myClass")     // By class — finds all elements with this class
$("p")            // By tag name — all <p> elements
$("div, p, span") // Multiple — comma means OR
$("div p")        // Descendant — space means "inside any level"
$("div > p")      // Child — > means "immediate child only"
$("div + p")      // Adjacent sibling — the <p> immediately after a <div>
$("div ~ p")      // General sibling — all <p> after a <div>

Combining Selectors

$("ul.menu")               // <ul> with class="menu"
$("input[type='text']")    // <input> where type="text"
$("div#content p:first")   // First <p> inside <div id="content">
$("ul > li.active")        // Direct <li class="active"> child of <ul>

Why combine? Because $("ul.menu") is more precise than $("ul") — it only matches the specific list you want, not every list on the page.

Attribute Selectors

Attributes are properties like href, src, type, or custom data-* attributes:

$("[href]")                        // Has ANY href attribute
$("[href='https://example.com']")  // Exact match
$("[href!='https://example.com']") // NOT equal to this value
$("[href$='.pdf']")                // Ends with ".pdf" — great for file types
$("[href^='https']")               // Starts with "https" — secure links only
$("[href*='example']")             // Contains "example" anywhere
$("[href~='keyword']")             // Contains the word "keyword" (space-separated)
$("[href|='en']")                  // Starts with "en" or equals "en"

// Multiple conditions
$("[href][title]")                 // Has BOTH href AND title
$("input[type='checkbox'][checked]") // Checked checkboxes

Real-World Attribute Selector Example

// In Durga Antivirus Pro's dashboard:
// Find all threat items with severity="critical"
$("[data-severity='critical']").addClass("blink-red");

// Find all external links in articles
$("a[href^='http']:not([href*='mysite.com'])").attr("target", "_blank");

jQuery Extension Selectors

These go beyond CSS — jQuery adds them specifically for easier DOM targeting.

Position Filters

$("li:first")        // First <li> in the entire document
$("li:last")         // Last <li>
$("li:first-child")  // <li> that is the first child of its parent
$("li:last-child")   // <li> that is the last child of its parent
$("li:nth-child(3)") // Third <li> within its parent (1-indexed)
$("li:nth-child(odd)") // Odd-positioned children

// jQuery-specific (not in CSS!)
$("li:eq(2)")        // Third <li> (0-indexed — starts at 0)
$("li:gt(2)")        // <li> after index 2 (indices 3, 4, 5...)
$("li:lt(2)")        // <li> before index 2 (indices 0, 1)
$("li:even")         // Even-indexed (0, 2, 4...)
$("li:odd")          // Odd-indexed (1, 3, 5...)

Wait, what’s the difference between :first and :first-child?

  • :first — the very first <li> in the entire jQuery selection
  • :first-child — any <li> that is the first child of its parent (there could be multiple)
<ul>
  <li>A</li>    <!-- :first → A, :first-child → A -->
  <li>B</li>
</ul>
<ul>
  <li>C</li>    <!-- :first-child → C -->
</ul>

Content Filters

$("div:contains('Hello')")   // <div> with text "Hello" anywhere
$("div:has(p)")              // <div> containing a <p> element
$("div:empty")               // <div> with no children at all
$("div:parent")              // <div> with at least one child (inverse of :empty)

Visibility Filters

$(":hidden")    // display:none, input type="hidden", width/height=0
$(":visible")   // Elements currently visible on screen

Other Useful Filters

$(":animated")      // Elements currently being animated
$(":focus")         // The element with keyboard focus
$(":header")        // All <h1> through <h6> elements
$(":not(.class)")   // Negation — everything NOT matching
$(":root")          // The <html> element
$(":target")        // Element matching the URL hash

Form Selectors

Forms have their own set of selectors that make working with inputs much easier:

// Element type selectors
$(":input")       // ALL input, textarea, select, button elements
$(":text")        // <input type="text">
$(":password")    // <input type="password">
$(":radio")       // <input type="radio">
$(":checkbox")    // <input type="checkbox">
$(":file")        // <input type="file">
$(":submit")      // <input type="submit"> or <button type="submit">
$(":reset")       // <input type="reset">
$(":button")      // <button> or <input type="button">

// State selectors
$(":enabled")     // Enabled form elements
$(":disabled")    // Disabled form elements
$(":checked")     // Checked checkboxes or radio buttons
$(":selected")    // Selected <option> elements

Practical Form Selector Patterns

// Highlight all form inputs on focus
$("form :input").focus(function() {
    $(this).css("border", "2px solid #1a73e8");
});

// Get the value of the selected radio button
var gender = $("input[name='gender']:checked").val();

// Count how many checkboxes are checked
var checkedCount = $("input[type='checkbox']:checked").length;

// Disable the submit button after first click
$(":submit").click(function() {
    $(this).prop("disabled", true).val("Submitting...");
});

Custom Selectors

For advanced cases, you can create your own selectors:

// Create a custom :startswith selector
$.expr[":"].startswith = function(el, index, meta, stack) {
    return $(el).text().trim().startsWith(meta[3]);
};

// Usage — find <li> whose text starts with "Urgent"
$("li:startswith(Urgent)");

JavaScript vs jQuery: Selectors

TaskVanilla JavaScriptjQuery
Select by IDdocument.getElementById("id")$("#id")
Select by classdocument.querySelectorAll(".cls")$(".cls")
Select first matchdocument.querySelector("p")$("p:first") or $("p").first()
Select by attributedocument.querySelectorAll("[data-id='5']")$("[data-id='5']")
Check if existsif (el)if ($("#id").length)

Selector Performance Tips

Not all selectors are created equal. Some are fast, some are slow:

// FASTEST — ID selector
$("#content");

// FAST — tag with context (narrow the search area)
$("td", "#dataTable");     // Equivalent to:
$("#dataTable").find("td");

// SLOW — complex attribute selectors on large DOM
$("[data-type='widget']");

// BETTER — narrow scope first
$("#widgetContainer").find("[data-type='widget']");

// SLOW — :has() checks every descendant
$("div:has(a[href^='https'])");

// FASTER — filter after narrowing
$("div").filter(function() {
    return $(this).find("a[href^='https']").length;
});

// ALWAYS cache repeated selections
var $menu = $("#menu");       // Query the DOM once
$menu.find("li").hide();      // Reuse the cached object
$menu.find("a").css(...);     // Reuse again

Common Mistakes

1. Forgetting the # for IDs

// WRONG — looks for a <myId> element tag
$("myId").hide();

// RIGHT — looks for id="myId"
$("#myId").hide();

2. Assuming :visible Means “On Screen”

:visible checks display !== "none", visibility !== "hidden", and opacity > 0. An element scrolled off-screen still counts as visible.

3. Using :contains Case-Sensitively

// This won't match <p>hello world</p>
$("p:contains('Hello')");  // Case-sensitive!

4. Not Escaping Special Characters

IDs or classes with dots or colons need escaping:

// If element has id="my.id" or id="my:id"
$("#my\\.id");       // Escape the dot
$("#my\\:id");       // Escape the colon
$("[id='my.id']");   // Attribute selector — no escaping needed

5. Using :has() in Large Documents

:has() traverses all descendants. For a 10,000-row table, this is slow. Use .has() method instead:

// SLOW on large DOM
$("div:has(a.external)");

// FASTER
$("div").has("a.external");

6. Confusing :eq() with :nth-child()

:eq(2) is 0-indexed (selects the 3rd element). :nth-child(2) is 1-indexed (selects the 2nd child of its parent). They behave very differently.

Practice Questions

1. What selector would you use to find all checked checkboxes?

$("input[type='checkbox']:checked") or $(":checkbox:checked").

2. What’s the difference between $("div p") and $("div > p")?

$("div p") selects all <p> inside <div> at any depth. $("div > p") selects only <p> that are direct children of <div>.

3. How do you select the third <li> in a list?

$("li:eq(2)") (0-indexed) or $("li:nth-child(3)") (1-indexed) or $("li").eq(2).

4. Challenge: Write a selector to find all <a> elements with href starting with “https” that are inside a <div> with class “article”, excluding those inside a <footer>.

Answer`$("div.article a[href^='https']:not(footer a)")` — combine attribute, descendant, and negation selectors.

FAQ

What is the difference between :first and :first-child?
:first selects the first element in the matched jQuery set. :first-child selects elements that are the first child of their parent. Given <ul><li>A</li><li>B</li></ul><ul><li>C</li></ul>, li:first returns A, li:first-child returns A and C.
Can I use CSS3 selectors in jQuery?
Yes, jQuery supports most CSS3 selectors and adds jQuery-specific extensions like :eq(), :gt(), :lt(), :odd, :even, :has().
What is the fastest jQuery selector?
ID selectors ($("#id")) are fastest because jQuery maps them to native getElementById(). Class selectors are next. Complex attribute selectors are slowest.
How do I select by data attributes?
Use the attribute selector: $("[data-user-id='42']"). To read the value, use $el.data("userId").
Can I negate multiple selectors?
Yes: $("li:not(.active):not(.disabled)") or $("li").not(".active, .disabled").
How do I select elements that contain specific text?
Use :contains(): $("p:contains('error')") finds all <p> containing the word “error”. Note it’s case-sensitive.

Try It Yourself

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Selector Playground</title>
    <style>
        body { font-family: system-ui, sans-serif; max-width: 600px; margin: 40px auto; }
        .highlight { background: #fff9c4 !important; }
        table { border-collapse: collapse; width: 100%; margin: 16px 0; }
        td, th { border: 1px solid #ccc; padding: 8px; }
        button { margin: 5px; padding: 8px 16px; cursor: pointer; }
        .controls { margin: 20px 0; }
        #result { margin-top: 12px; padding: 8px; background: #f5f5f5; border-radius: 4px; }
    </style>
</head>
<body>
    <h1>Selector Playground</h1>

    <div class="controls">
        <button data-selector="li:first">:first</button>
        <button data-selector="li:last">:last</button>
        <button data-selector="li:even">:even</button>
        <button data-selector="li:odd">:odd</button>
        <button data-selector="li:eq(2)">:eq(2)</button>
        <button data-selector="li:gt(2)">:gt(2)</button>
        <button data-selector="input:enabled">:enabled</button>
        <button data-selector=":checkbox:checked">:checked</button>
        <button data-selector="*">Clear</button>
    </div>

    <ul id="itemList">
        <li>Item 1</li>
        <li>Item 2</li>
        <li>Item 3</li>
        <li>Item 4</li>
        <li>Item 5</li>
    </ul>

    <form>
        <input type="text" value="Hello"><br>
        <input type="checkbox" checked> Checked<br>
        <input type="checkbox"> Unchecked<br>
        <input type="checkbox" checked> Also Checked<br>
        <button type="button">Button</button>
    </form>

    <div id="result">Click a selector button to see results</div>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <script>
        $(function() {
            $("button[data-selector]").click(function() {
                var selector = $(this).data("selector");
                $("*").removeClass("highlight");
                if (selector === "*") {
                    $("#result").text("Cleared all highlights");
                    return;
                }
                $(selector).addClass("highlight");
                var count = $(selector).length;
                $("#result").text('Selector "' + selector + '" matched ' + count + ' element(s)');
            });
        });
    </script>
</body>
</html>

What’s Next

TopicDescription
https://tutorials.dodatech.com/frameworks/jquery/jquery-events/Handle user interactions on selected elements
https://tutorials.dodatech.com/frameworks/jquery/jquery-dom/Manipulate content and attributes of selected elements
https://tutorials.dodatech.com/frameworks/jquery/jquery-traversing/Navigate the DOM tree from your selections
CSSCSS selector syntax reference (shared with jQuery)
HTMLHTML attributes and data attribute patterns

What’s Next

Congratulations on completing this Jquery Selectors tutorial! Here’s where to go from here:

  • Practice daily — Consistency is more important than long study sessions
  • Build a project — Apply what you learned by building something real
  • Explore related topics — Check out other tutorials in the same category
  • Join the community — Discuss with other learners and share your progress

Remember: every expert was once a beginner. Keep coding!

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro