JAVASCRIPT Archives - SANSKAR'S CODE https://sanskarsontakke.com/category/javascript/ Elevating Ideas through Code Thu, 06 Feb 2025 13:49:36 +0000 en-US hourly 1 https://wordpress.org/?v=6.7.1 jQuery Selectors: A Comprehensive Guide with Examples https://sanskarsontakke.com/2025/02/06/jquery-selectors-a-comprehensive-guide-with-examples/ https://sanskarsontakke.com/2025/02/06/jquery-selectors-a-comprehensive-guide-with-examples/#respond Thu, 06 Feb 2025 13:49:36 +0000 https://sanskarsontakke.com/?p=211 Introduction to jQuery Selectors jQuery is a fast, lightweight, and feature-rich JavaScript library that simplifies HTML document manipulation. One of its core features is selectors, which allow developers to find and manipulate HTML elements easily. jQuery selectors are inspired by CSS selectors but come with additional functionalities that make DOM traversal even more powerful. In ... Read more

The post jQuery Selectors: A Comprehensive Guide with Examples appeared first on SANSKAR'S CODE.

]]>
Introduction to jQuery Selectors

jQuery is a fast, lightweight, and feature-rich JavaScript library that simplifies HTML document manipulation. One of its core features is selectors, which allow developers to find and manipulate HTML elements easily. jQuery selectors are inspired by CSS selectors but come with additional functionalities that make DOM traversal even more powerful.

In this article, we will explore jQuery Selectors with suitable examples and explanations.


1. Basic Selectors in jQuery

1.1 The Universal Selector (*)

The * selector selects all elements on a web page.

Example:

<!DOCTYPE html>
<html>
<head>
    <title>Universal Selector Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function(){
            $("*").css("color", "blue");
        });
    </script>
</head>
<body>
    <h1>Heading</h1>
    <p>Paragraph 1</p>
    <p>Paragraph 2</p>
</body>
</html>

Explanation:

The * selector applies the color: blue style to all elements in the document.


1.2 ID Selector (#id)

The #id selector selects an element by its unique ID.

Example:

<p id="myPara">This is a paragraph.</p>

<script>
    $(document).ready(function(){
        $("#myPara").css("color", "red");
    });
</script>

Explanation:

The paragraph with id="myPara" is selected and its text color is changed to red.


1.3 Class Selector (.class)

The .class selector selects all elements with a specific class name.

Example:

<p class="highlight">Paragraph 1</p>
<p class="highlight">Paragraph 2</p>

<script>
    $(document).ready(function(){
        $(".highlight").css("background-color", "yellow");
    });
</script>
Explanation:
All elements with the class highlight get a yellow background.

1.4 Element Selector (tagname)
The tagname selector selects all elements with the specified tag.

Example:
<h2>Heading 1</h2>
<h2>Heading 2</h2>

<script>
    $(document).ready(function(){
        $("h2").css("font-size", "30px");
    });
</script>

Explanation:

All <h2> elements have their font size increased to 30px.


2. Attribute Selectors in jQuery

2.1 Selecting Elements with a Specific Attribute

Use [attribute] to select elements that have a specific attribute.

Example:

<input type="text" placeholder="Enter Name">
<input type="password">

<script>
    $(document).ready(function(){
        $("[placeholder]").css("border", "2px solid green");
    });
</script>

Explanation:

All elements with a placeholder attribute receive a green border.


2.2 Selecting Elements with a Specific Attribute Value

Use [attribute="value"] to select elements with a specific attribute value.

Example:

<input type="text">
<input type="password">

<script>
    $(document).ready(function(){
        $("input[type='password']").css("background-color", "lightgray");
    });
</script>

Explanation:

Only <input> elements with type="password" will have a light gray background.


3. Hierarchical Selectors in jQuery

3.1 Child Selector (parent > child)

Selects direct child elements of a parent.

Example:

<div>
    <p>Paragraph inside div</p>
    <span><p>Nested paragraph</p></span>
</div>

<script>
    $(document).ready(function(){
        $("div > p").css("color", "blue");
    });
</script>

Explanation:

Only direct <p> children inside <div> are selected, excluding nested <p> inside <span>.


3.2 Descendant Selector (ancestor descendant)

Selects all descendant elements.

Example:

<div>
    <p>Paragraph inside div</p>
    <span><p>Nested paragraph</p></span>
</div>

<script>
    $(document).ready(function(){
        $("div p").css("color", "green");
    });
</script>

Explanation:

All <p> elements inside <div>, whether directly inside or nested, are selected.


4. Filtering Selectors in jQuery

4.1 First and Last Element Selectors (:first and :last)

Selects the first and last element in a group.

Example:

<ul>
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
</ul>

<script>
    $(document).ready(function(){
        $("li:first").css("font-weight", "bold");
        $("li:last").css("color", "red");
    });
</script>

Explanation:

  • The first <li> is made bold.
  • The last <li> turns red.

4.2 Even and Odd Elements Selectors (:even and :odd)

Selects elements based on even and odd index numbers.

Example:

<ul>
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
    <li>Item 4</li>
</ul>

<script>
    $(document).ready(function(){
        $("li:even").css("background-color", "lightblue");
        $("li:odd").css("background-color", "lightgray");
    });
</script>

Explanation:

  • Even-indexed <li> elements get a blue background.
  • Odd-indexed <li> elements get a gray background.

4.3 Selecting Hidden Elements (:hidden)

Used to select elements that are hidden using display: none or visibility: hidden.

Example:

<p style="display: none;">This is a hidden paragraph.</p>

<script>
    $(document).ready(function(){
        $(":hidden").show();
    });
</script>

Conclusion

jQuery selectors are a powerful way to manipulate DOM elements efficiently. By mastering these selectors, developers can write cleaner and more effective jQuery code for their web applications.

The post jQuery Selectors: A Comprehensive Guide with Examples appeared first on SANSKAR'S CODE.

]]>
https://sanskarsontakke.com/2025/02/06/jquery-selectors-a-comprehensive-guide-with-examples/feed/ 0
Understanding jQuery’s first(), last(), eq(), filter(), and not() Methods with Examples https://sanskarsontakke.com/2025/02/06/understanding-jquerys-first-last-eq-filter-and-not-methods-with-examples/ https://sanskarsontakke.com/2025/02/06/understanding-jquerys-first-last-eq-filter-and-not-methods-with-examples/#respond Thu, 06 Feb 2025 13:38:19 +0000 https://sanskarsontakke.com/?p=209 Introduction In jQuery, selection methods allow us to filter and refine elements efficiently. Five essential methods that help manipulate element selections are: first() last() eq() filter() not() These methods provide precise control over DOM elements, making your code cleaner and more effective. Let’s explore each method with examples. 1. jQuery first() Method Definition: The first() ... Read more

The post Understanding jQuery’s first(), last(), eq(), filter(), and not() Methods with Examples appeared first on SANSKAR'S CODE.

]]>
Introduction

In jQuery, selection methods allow us to filter and refine elements efficiently. Five essential methods that help manipulate element selections are:

  • first()
  • last()
  • eq()
  • filter()
  • not()

These methods provide precise control over DOM elements, making your code cleaner and more effective. Let’s explore each method with examples.

1. jQuery first() Method

Definition:

The first() method selects only the first element from a matched set.

Syntax:

$(selector).first();

Example:

<!DOCTYPE html>
<html>
<head>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <ul>
        <li>Item 1</li>
        <li>Item 2</li>
        <li>Item 3</li>
    </ul>
    <button id="btn">Highlight First Item</button>

    <script>
        $(document).ready(function(){
            $("#btn").click(function(){
                $("li").first().css("color", "red");
            });
        });
    </script>
</body>
</html>

2. jQuery last() Method

Definition:

The last() method selects only the last element from a matched set.

Syntax:

$(selector).last();

Example:

$("li").last().css("color", "blue");

Explanation:

  • This method targets the last <li> element and changes its color to blue.

3. jQuery eq() Method

Definition:

The eq(n) method selects the element at index n from a matched set. Indexing starts from 0.

Syntax:

$(selector).last();

Explanation:

  • This method targets the last <li> element and changes its color to blue.

3. jQuery eq() Method

Definition:

The eq(n) method selects the element at index n from a matched set. Indexing starts from 0.

Syntax:

$(selector).eq(index);
$("li").eq(1).css("font-weight", "bold");

4. jQuery filter() Method

Definition:

The filter(selector/function) method filters elements based on a selector or function.

Syntax:

$(selector).filter(criteria);

Example:

$("li").filter(":even").css("background-color", "lightgray");

Explanation:

  • Selects and applies a background color to even-indexed <li> elements.

 

5. jQuery not() Method

Definition:

The not(selector/function) method removes elements that match a specified condition.

Syntax:

$(selector).not(criteria);

Example:

$("li").not(":first").css("text-decoration", "underline");

Explanation:

  • All <li> elements except the first one will have underlined text.

Conclusion

These five jQuery methods—first(), last(), eq(), filter(), and not()—help in efficiently selecting and manipulating elements in a webpage. By mastering these, you can refine your jQuery-based scripts for better performance and readability.

 

The post Understanding jQuery’s first(), last(), eq(), filter(), and not() Methods with Examples appeared first on SANSKAR'S CODE.

]]>
https://sanskarsontakke.com/2025/02/06/understanding-jquerys-first-last-eq-filter-and-not-methods-with-examples/feed/ 0
Mastering jQuery toggleClass(): 5 Practical Examples for Dynamic Styling https://sanskarsontakke.com/2025/02/06/mastering-jquery-toggleclass-5-practical-examples-for-dynamic-styling/ https://sanskarsontakke.com/2025/02/06/mastering-jquery-toggleclass-5-practical-examples-for-dynamic-styling/#respond Thu, 06 Feb 2025 13:23:30 +0000 https://sanskarsontakke.com/?p=207 The toggleClass() method in jQuery is used to toggle (add or remove) one or more classes from the selected elements. If the specified class is present, it removes it; if not, it adds it. This method is useful for dynamically changing styles based on user interaction.   $(selector).toggleClass(className, [switch]) className: A string containing one or ... Read more

The post Mastering jQuery toggleClass(): 5 Practical Examples for Dynamic Styling appeared first on SANSKAR'S CODE.

]]>
The toggleClass() method in jQuery is used to toggle (add or remove) one or more classes from the selected elements. If the specified class is present, it removes it; if not, it adds it. This method is useful for dynamically changing styles based on user interaction.

 

$(selector).toggleClass(className, [switch])

className: A string containing one or more class names to toggle.

switch (optional): A Boolean value (true to add the class, false to remove it).

Examples

Example 1: Basic toggleClass()

Toggles a class on a button click

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>toggleClass Example 1</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <style>
        .highlight {
            background-color: yellow;
            font-weight: bold;
        }
    </style>
</head>
<body>

<p id="text">Click the button to toggle the highlight class.</p>
<button id="btn">Toggle Class</button>

<script>
    $(document).ready(function(){
        $("#btn").click(function(){
            $("#text").toggleClass("highlight");
        });
    });
</script>

</body>
</html>

Explanation:

  • When the button is clicked, the highlight class is toggled on the <p> element.
  • If the class is not present, it is added.
  • If already present, it is removed.

Example 2: Using toggleClass() with Multiple Classes

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>toggleClass Example 2</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <style>
        .red { color: red; }
        .bold { font-weight: bold; }
    </style>
</head>
<body>

<p id="text">Click the button to toggle multiple classes.</p>
<button id="btn">Toggle Multiple Classes</button>

<script>
    $(document).ready(function(){
        $("#btn").click(function(){
            $("#text").toggleClass("red bold");
        });
    });
</script>

</body>
</html>

Explanation:

  • The toggleClass() method is used with multiple classes (red and bold).
  • Clicking the button adds or removes both classes together.

Example 3: Using toggleClass() with a Condition (Boolean)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>toggleClass Example 3</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <style>
        .large-text {
            font-size: 24px;
        }
    </style>
</head>
<body>

<p id="text">Click the buttons to add or remove the class.</p>
<button id="add">Add Class</button>
<button id="remove">Remove Class</button>

<script>
    $(document).ready(function(){
        $("#add").click(function(){
            $("#text").toggleClass("large-text", true); // Always adds class
        });

        $("#remove").click(function(){
            $("#text").toggleClass("large-text", false); // Always removes class
        });
    });
</script>

</body>
</html>

 

Explanation:

  • If true is passed, the class is always added.
  • If false is passed, the class is always removed.
  • This ensures no toggling, just explicit addition or removal.

Example 4: Using toggleClass() on Multiple Elements

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>toggleClass Example 4</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <style>
        .selected {
            background-color: lightblue;
        }
    </style>
</head>
<body>

<ul>
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
    <li>Item 4</li>
</ul>

<script>
    $(document).ready(function(){
        $("li").click(function(){
            $(this).toggleClass("selected");
        });
    });
</script>

</body>
</html>

Explanation:

  • Clicking on any <li> item will toggle the selected class for that specific item.
  • Each <li> works independently.

Example 5: ToggleClass() for Dark Mode

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>toggleClass Example 5</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <style>
        body {
            transition: background 0.3s, color 0.3s;
        }
        .dark-mode {
            background-color: black;
            color: white;
        }
    </style>
</head>
<body>

<button id="toggle">Toggle Dark Mode</button>

<script>
    $(document).ready(function(){
        $("#toggle").click(function(){
            $("body").toggleClass("dark-mode");
        });
    });
</script>

</body>
</html>

Explanation:

  • Clicking the button toggles a “dark mode” effect by changing background and text color.

Summary

Example Description
Example 1 Basic toggleClass() usage
Example 2 Toggling multiple classes at once
Example 3 Using toggleClass() with a Boolean condition
Example 4 Applying toggleClass() to multiple elements
Example 5 Implementing a dark mode toggle

The post Mastering jQuery toggleClass(): 5 Practical Examples for Dynamic Styling appeared first on SANSKAR'S CODE.

]]>
https://sanskarsontakke.com/2025/02/06/mastering-jquery-toggleclass-5-practical-examples-for-dynamic-styling/feed/ 0