jQuery DOM Manipulation and Element Operations

CSS Class Operations

addClass(); // Applies specified CSS class
removeClass(); // Removes specified CSS class
hasClass(); // Checks for class existence
toggleClass(); // Toggles class state

Example: Light switch and modal dialogs

CSS Property Manipulation

css("color","red") // DOM equivalent: element.style.color = "red"

Usage example:

$("p").css("color", "blue"); // Changes all paragraph text to blue

Element Positioning

offset() // Gets/sets position relative to document
position() // Gets position relative to parent element
scrollTop() // Gets/sets vertical scroll position
scrollLeft() // Gets/sets horizontal scroll position

The .offset() method retrieves element position relative to the document, while .position() returns position relative to the parent element.

Back-to-top implementation example:

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Scroll Position Example</title>
  <style>
    .content-box {
      width: 100px;
      height: 200px;
      background-color: #ff6b6b;
    }
    .scroll-top-btn {
      height: 50px;
      width: 50px;
      position: fixed;
      bottom: 15px;
      right: 15px;
      background-color: #4ecdc4;
    }
    .hidden {
      display: none;
    }
    .spacer {
      height: 100px;
    }
  </style>
</head>
<body>
<button id="positionBtn">Adjust Position</button>
<div class="content-box"></div>
<div class="spacer">Content 1</div>
<div class="spacer">Content 2</div>
<!-- Additional content divs -->
<button id="topBtn" class="scroll-top-btn hidden">Top</button>

<script src="jquery-3.6.0.min.js"></script>
<script>
  $("#positionBtn").on("click", function() {
    $(".content-box").offset({left: 250, top: 250});
  });

  $(window).scroll(function() {
    if ($(window).scrollTop() > 150) {
      $("#topBtn").removeClass("hidden");
    } else {
      $("#topBtn").addClass("hidden");
    }
  });
  
  $("#topBtn").on("click", function() {
    $(window).scrollTop(0);
  });
</script>
</body>
</html>

Dimension Methods

height()
width()
innerHeight()
innerWidth()
outerHeight()
outerWidth()

Content Manipulation

HTML content:

html() // Gets HTML content of first matched element
html(content) // Sets HTML content for all matched elements

Text content:

text() // Gets text content of all matched elements
text(content) // Sets text content for all matched elements

Form values:

val() // Gets current value of first matched element
val(value) // Sets value for all matched elements
val([value1, value2]) // Sets values for multi-select elements

Example with checkboxes:

<input type="checkbox" value="tennis" name="sports">Tennis
<input type="checkbox" value="swimming" name="sports">Swimming

<select multiple id="multiSelect">
    <option value="a">Option A</option>
    <option value="b">Option B</option>
    <option value="c">Option C</option>
</select>

Setting values:

$("[name='sports']").val(['tennis', 'swimming']);
$("#multiSelect").val(["a", "b"]);

Retreiving selected radio button value:

<label for="female">Female</label>
<input name="gender" id="female" type="radio" value="F">
<label for="male">Male</label>
<input name="gender" id="male" type="radio" value="M">

JavaScript retrieval:

$("input[name='gender']:checked").val();

Attribute Operations

For standard and custom attributes:

attr(attributeName) // Returns attribute value
attr(attributeName, value) // Sets attribute value
attr({key1: value1, key2: value2}) // Sets multiple attributes
removeAttr() // Removes attribute

For boolean properties (checkboxes, radio buttons):

prop() // Gets property value
removeProp() // Removes property

Important distinction: Use prop() for boolean properties like checked, selected, or disabled states. Use attr() for standard HTML attributes.

Example:

<input type="checkbox" value="option1">
<input type="radio" value="option2">
<script>
  $(":checkbox[value='option1']").prop("checked", true);
  $(":radio[value='option2']").prop("checked", true);
</script>

Document Manipulation

Appending to element interior (end):

let newParagraph = $('<p>');
newParagraph.text('Dynamic content added');
newParagraph.attr('id','newElement');
$('#container').append(newParagraph); // Appends to end

// Alternative syntax:
$(A).append(B) // Appends B to A
$(A).appendTo(B) // Appends A to B

Prepending to element interior (beginning):

$(A).prepend(B) // Prepends B to A
$(A).prependTo(B) // Prepends A to B

Inserting after element (exterior):

$(A).after(B) // Places B after A
$(A).insertAfter(B) // Places A after B

Element removal:

remove() // Removes element from DOM
empty() // Removes all child nodes

Element replacement:

replaceWith()
replaceAll()

Element cloning:

clone() // Basic cloning
clone(true) // Clones with event handlers

Cloning example:

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Element Cloning</title>
  <style>
    .clone-btn {
      padding: 8px;
      color: white;
      margin: 8px;
      border: none;
      border-radius: 4px;
    }
    #clone1 { background-color: #e74c3c; }
    #clone2 { background-color: #3498db; }
  </style>
</head>
<body>
<button id="clone1">Clone without events</button>
<hr>
<button id="clone2">Clone with events</button>

<script src="jquery-3.6.0.min.js"></script>
<script>
  // Clone without event handlers
  $("#clone1").on("click", function() {
    $(this).clone().insertAfter(this);
  });
  
  // Clone with event handlers
  $("#clone2").on("click", function() {
    $(this).clone(true).insertAfter(this);
  });
</script>
</body>
</html>

Tags: jquery DOM Manipulation javascript web development frontend

Posted on Thu, 07 May 2026 16:53:14 +0000 by andychamberlainuk