操作 DOM
现在,您已经学会了 Cheerio 使用的基础知识,并获得了一些 加载和遍历文档的经验,是时候深入学习如何 操作元素了。无论你是想修改元素的属性、 添加和删除 class、修改文本和 HTML 内容,还是插入和 删除元素,Cheerio 都提供了一系列方法来帮助你完成这些操作。
在本指南中,我们将重点介绍如何使用 Cheerio 操作文档中的元素。 我们将介绍的一些方法来修改元素属性、 添加和删除 class、修改 文本和 HTML 内容、 插入和删除元素以及处理错误和调试。在学完本指南 时,你将对如何使用 Cheerio 所提供的这些方法来 操作元素有一个很好的了解。
修改元素的属性
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.
要修改单个元素的属性,可以分别使用
attr()
和
prop()
方法。这两个方法都将一个键和一个值作为参数,允许你获取和设置属性。设置时,它们适用于选区中的所有元素;获取时,它们返回与选区中第一个元素相对应的单个值。
// 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');
Modifying the Text Content of an Element
To query or modify the text content of an element, you can use the
text()
method. Given a string as an
argument, it sets the text content of every element in the selection to the
given string. Without arguments, it returns the text content of every element
(including its descendants) in the selection, concatenated together.
// Set the text content of an element
$('h1').text('Hello, World!');
// Get the text content of an element
const text = $('p').text();