DOM の操作
Cheerio の基本的な使用方法と、ドキュメントの読み込みとトラバースに関する経験を積んだので、次は要素の操作について詳しく見ていきましょう。要素の属性とプロパティの変更、クラスの追加と削除、テキストとHTMLコンテンツの変更、要素の挿入と削除など、Cheerio はこれらを行うための様々なメソッドを提供しています。
このガイドでは、Cheerio を使用したドキュメント内の要素操作に焦点を当てます。要素の属性とプロパティの変更、クラスの追加と削除、テキストとHTMLコンテンツの変更、要素の挿入と削除、エラー処理とデバッグの方法について説明します。このガイドの最後までに、Cheerio を使用してドキュメント内の要素を操作する方法を十分に理解できるようになります。
要素属性とプロパティの変更
単一要素の属性とプロパティを変更するには、それぞれ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()
は、文字列やブール値のような単純な値に限定されません。style
オブジェクトのような複雑なプロパティを取得したり、サポートされている要素のhref
やsrc
URLを解決したりすることもできます。また、単一要素のtagName
、innerHTML
、outerHTML
、textContent
、innerText
プロパティを取得することもできます。
// 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');
クラスの追加と削除
要素からクラスを追加または削除するには、addClass()
、removeClass()
、toggleClass()
メソッドを使用できます。これら3つのメソッドはすべて、クラス名またはスペースで区切られたクラス名のリストを引数として受け取ります。選択されたすべての要素が変更されます。
// 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');
要素のテキストコンテンツの変更
要素のテキストコンテンツを照会または変更するには、text()
メソッドを使用できます。文字列を引数として与えると、選択されたすべての要素のテキストコンテンツが指定された文字列に設定されます。引数がない場合は、選択されたすべての要素(子孫要素を含む)のテキストコンテンツを連結して返します。
// Set the text content of an element
$('h1').text('Hello, World!');
// Get the text content of an element
const text = $('p').text();
text()
は、渡されたすべての要素のtextContent
を返します。結果には、<script>
要素と<style>
要素の内容も含まれます。これを避けるには、代わりに.prop('innerText')
を使用してください。
要素のHTMLコンテンツの変更
要素のHTMLコンテンツを照会または変更するには、html()
メソッドを使用できます。HTML文字列を引数として与えると、選択されたすべての要素の内部HTMLが指定された文字列に設定されます。引数がない場合は、選択された最初の要素の内部HTMLを返します。
// Set the inner HTML of an element
$('div').html('<p>Hello, World!</p>');
// Get the inner HTML of an element
const html = $('div').html();
新しい要素の挿入
ドキュメントに新しい要素を挿入するには、append()
、prepend()
、before()
、after()
メソッドを使用できます。これらは選択されたすべての要素を変更します。
// Append an element to the end of a parent element
$('ul').append('<li>Item</li>');
// Prepend an element to the beginning of a parent element
$('ul').prepend('<li>Item</li>');
// Insert an element before a target element
$('li').before('<li>Item</li>');
// Insert an element after a target element
$('li').after('<li>Item</li>');
insertAfter()
メソッドとinsertBefore()
メソッドを使用すると、それぞれターゲット要素の前または後に要素を挿入できます。どちらのメソッドも、文字列またはCheerioオブジェクトを引数として受け取り、指定された要素をターゲット要素の前または後に挿入します。
const $ = require('cheerio');
// Insert an element after a target element
$('<p>Inserted element</p>').insertAfter('h1');
// Insert an element before a target element
$('<p>Inserted element</p>').insertBefore('h1');
prependTo()
メソッドとappendTo()
メソッドを使用すると、それぞれ親要素の先頭または末尾に要素を追加できます。どちらのメソッドも、文字列またはCheerioオブジェクトを引数として受け取り、指定された親要素の先頭または末尾に要素を挿入します。
const $ = require('cheerio');
// Prepend an element to a parent element
$('<p>Inserted element</p>').prependTo('div');
// Append an element to a parent element
$('<p>Inserted element</p>').appendTo('div');
要素のラップとアンラップ
要素を別の要素でラップしたり、子要素を保持したまま要素の親要素を削除したい場合があります。これを行うには、wrap()
、wrapInner()
、unwrap()
メソッドを使用できます。
wrap()
メソッドは、文字列またはCheerioオブジェクトを引数として受け取り、指定された要素で要素をラップします。
// Wrap an element in a div
$('p').wrap('<div></div>');
wrapInner()
メソッドはwrap()
と似ていますが、要素自体をラップするのではなく、要素の内部HTMLを指定された要素でラップします。
// Wrap the inner HTML of an element in a div
$('div').wrapInner('<div></div>');
unwrap()
メソッドは、要素とその子要素を保持したまま、要素の親要素を削除します。
// Unwrap an element
$('p').unwrap();
要素の置換
要素を別の要素で置換するには、replaceWith()
メソッドを使用できます。文字列またはCheerioオブジェクトを引数として受け取り、選択された各要素を指定された要素で置換します。
// Replace an element with another element
$('li').replaceWith('<li>Item</li>');
replaceWith()
メソッドは、ドキュメントから要素を削除し、指定された要素またはHTML文字列で置き換えることに注意してください。要素を保持してコンテンツを変更する場合は、代わりにhtml()
またはtext()
メソッドを使用できます。
要素の削除
ドキュメントから要素を削除するには、remove()
メソッドを使用できます。選択された各要素とそのすべての子要素がドキュメントから削除されます。
// Remove an element from the document
$('li').remove();
あるいは、要素自体を削除せずに、ドキュメントから要素の子要素を削除するには、empty()
メソッドを使用できます。選択された各要素の子要素(テキストノードやコメントを除く)がドキュメントから削除されます。
// Remove an element's children from the document
$('li').empty();
結論
Cheerio を使用してドキュメント内の要素を操作する方法を学習しました。要素の属性とプロパティの変更、クラスの追加と削除、テキストとHTMLコンテンツの変更、要素の挿入と削除、エラー処理とデバッグを行うことができます。これらのツールを使用することで、必要に応じて簡単にドキュメントを操作できます。