JavaScript / jQuery HTML Elements

Manipulating HTML elements is a fundamental part of building dynamic and interactive web applications. Both JavaScript and jQuery offer powerful tools for selecting, modifying, and creating HTML elements.

Manipulating HTML Elements with JavaScript

JavaScript provides native methods to work with HTML elements.

Selecting Elements

  • By ID: let element = document.getElementById('myId');
  • By Class: let elements = document.getElementsByClassName('myClass');
  • By Tag Name: let elements = document.getElementsByTagName('div');

Creating and Appending Elements

  • Create a New Element: let newElement = document.createElement('p'); newElement.textContent = 'Hello World!';
  • Append the Element: document.body.appendChild(newElement);

Modifying Content

  • Set Content: element.innerHTML = '<b>New Content</b>';
  • Get Content: let content = element.innerHTML;

Modifying Attributes

  • Set an Attribute: element.setAttribute('class', 'newClass');
  • Get an Attribute: let className = element.getAttribute('class');

Removing Elements

  • Remove an Element: element.remove();

Manipulating HTML Elements with jQuery

jQuery simplifies these tasks with a concise and unified syntax.

Selecting Elements

  • By ID: let element = $('#myId');
  • By Class: let elements = $('.myClass');

Creating and Appending Elements

  • Create a New Element: let newElement = $('<p>Hello World!</p>');
  • Append the Element: $('body').append(newElement);

Modifying Content

  • Set Content: $('#myId').html('<b>New Content</b>');
  • Get Content: let content = $('#myId').html();

Modifying Attributes

  • Set an Attribute: $('#myId').attr('class', 'newClass');
  • Get an Attribute: let className = $('#myId').attr('class');

Removing Elements

  • Remove an Element: $('#myId').remove();

Key Differences Between JavaScript and jQuery for HTML Manipulation

AspectJavaScriptjQuery
SyntaxVerboseConcise and chainable
Learning CurveHigher for beginnersEasier and beginner-friendly
PerformanceFaster due to direct DOM manipulationSlightly slower due to abstraction

Example: Adding a New Paragraph

Using JavaScript:

let paragraph = document.createElement('p');
paragraph.textContent = 'This is a new paragraph!';
document.body.appendChild(paragraph);

Using jQuery:

$('body').append('<p>This is a new paragraph!</p>');

For more tutorials and tips, visit The Coding College.

Leave a Comment