This tutorial aims to guide you through the process of selecting and manipulating DOM (Document Object Model) elements using jQuery, a popular JavaScript library.
Basic knowledge of HTML, CSS, and JavaScript is required. Familiarity with jQuery would be beneficial but is not necessary.
DOM is a programming interface for HTML and XML documents. It represents the structure of a document and allows programming languages to interact with the document's content, structure, and styles.
jQuery provides several methods to select elements, the most common one is $('selector')
, where 'selector' can be any CSS selector.
jQuery allows you to manipulate the selected elements in various ways. You can change their content with .html()
, .text()
, and .val()
methods; their attributes with .attr()
, .removeAttr()
, and .prop()
methods; and their styles with .css()
method.
// Selecting all <p> elements
var pElements = $('p');
// Selecting element with id "myDiv"
var myDiv = $('#myDiv');
// Selecting all elements with class "myClass"
var myClassElements = $('.myClass');
// Changing the text content of the first <p> element
$('p:first').text('New text content');
// Changing the HTML content of the element with id "myDiv"
$('#myDiv').html('<strong>New bold content</strong>');
// Changing the 'src' attribute of the first <img> element
$('img:first').attr('src', 'newImage.jpg');
// Removing the 'disabled' attribute of the first <input> element
$('input:first').removeAttr('disabled');
// Changing the color of all <p> elements
$('p').css('color', 'blue');
// Changing multiple styles at once
$('#myDiv').css({
'background-color': 'yellow',
'font-size': '20px'
});
In this tutorial, we learned about the DOM and how to select and manipulate its elements using jQuery. You now know how to change the content, attributes, and styles of these elements.
To continue learning, you might want to explore more about jQuery events, animations, and AJAX.
Exercise 1: Select all <div>
elements with class 'info' and change their text content to 'Info'.
Solution:
$('.info').text('Info');
Exercise 2: Select the <input>
element with id 'myInput', remove its 'readonly' attribute, and change its value to 'Editable'.
Solution:
$('#myInput').removeAttr('readonly').val('Editable');
Exercise 3: Select all <p>
elements and change their color to 'red' and font size to '18px'.
Solution:
$('p').css({
'color': 'red',
'font-size': '18px'
});
Keep practicing with more complex selectors and manipulations. Happy coding!