Manipulating the DOM
Now that you have learned the basics of using Cheerio and have gained some experience with loading and traversing documents, it's time to dive deeper into manipulating elements. Whether you want to modify element attributes and properties, add and remove classes, modify text and HTML content, or insert and remove elements, Cheerio provides a range of methods to help you do so.
In this guide, we will focus specifically on manipulating elements within a document using Cheerio. We will cover methods for modifying element attributes and properties, adding and removing classes, modifying text and HTML content, inserting and removing elements, and handling errors and debugging. By the end of this guide, you will have a good understanding of how to use these methods to manipulate elements within a document using Cheerio.
Modifying Element Attributes and Properties
To modify the attributes and properties of a single element, you can use the
attr()
and
prop()
methods, respectively. Both methods
take a key and a value as arguments, and allow you to get and set the attribute
or property. When setting, they apply to all elements in the selection; when
getting, they return a single value corresponding to the first element in the
selection.
// Set the 'src' attribute of an image element
$('img').attr('src', 'https://example.com/image.jpg');
// Set the 'checked' property of a checkbox element
$('input[type="checkbox"]').prop('checked', true);
// Get the 'href' attribute of a link element
const href = $('a').attr('href');
// Get the 'disabled' property of a button element
const isDisabled = $('button').prop('disabled');
prop()
is not limited to simple values like strings and booleans. You can also
use it to get complex properties like the style
object, or to resolve href
or src
URLs of supported elements. You can also use it to get the tagName
,
innerHTML
, outerHTML
, textContent
, and innerText
properties of a single
element.
// Get the `style` object of an element
const style = $('div').prop('style');
// Get the resolved `src` URL of an image element
$('img').prop('src');
// Get the outerHTML of an element
const outerHTML = $('div').prop('outerHTML');
// Get the innerText of an element
const innerText = $('div').prop('innerText');
Adding and Removing Classes
To add or remove classes from an element, you can use the
addClass()
,
removeClass()
, and
toggleClass()
methods. All three
methods take a class name or a space-separated list of class names as an
argument. They modify all elements in the selection.
// Add a class to an element
$('div').addClass('new-class');
// Add multiple classes to an element
$('div').addClass('new-class another-class');
// Remove a class from an element
$('div').removeClass('old-class');
// Remove multiple classes from an element
$('div').removeClass('old-class another-class');
// Toggle a class on an element (add if it doesn't exist, remove if it does)
$('div').toggleClass('active');