5月29日 00:51

What are the DOM manipulation methods in Cheerio? How to use these methods?

Cheerio provides rich DOM manipulation methods that are highly compatible with jQuery's API. Here are the commonly used DOM manipulation methods:

1. Getting and Setting Content

javascript
// Get text content $('p').text(); // Get text of first matched element $('p').text('New text'); // Set text of all matched elements // Get HTML content $('.container').html(); // Get HTML of first matched element $('.container').html('<p>New</p>'); // Set HTML of all matched elements // Get form value $('input').val(); // Get input value $('input').val('new value'); // Set input value // Get attribute value $('a').attr('href'); // Get href attribute $('a').attr('href', 'new-url'); // Set href attribute $('a').attr({ // Set multiple attributes href: 'new-url', target: '_blank' }); $('a').removeAttr('target'); // Remove attribute // Get data attribute $('div').data('id'); // Get data-id $('div').data('id', '123'); // Set data-id

2. CSS Class Manipulation

javascript
// Add class $('div').addClass('active'); $('div').addClass('active highlight'); // Remove class $('div').removeClass('active'); $('div').removeClass('active highlight'); // Toggle class $('div').toggleClass('active'); // Check class $('div').hasClass('active'); // Returns true/false // Get class names $('div').attr('class'); // Get all class names

3. CSS Style Manipulation

javascript
// Get style $('div').css('color'); // Get color style // Set style $('div').css('color', 'red'); $('div').css({ // Set multiple styles color: 'red', fontSize: '14px', backgroundColor: '#f0f0f0' });

4. DOM Traversal

javascript
// Find child elements $('div').find('p'); // Find all descendant p elements $('div').children(); // Get direct child elements $('div').children('p'); // Get direct child p elements // Parent elements $('p').parent(); // Get direct parent element $('p').parents(); // Get all ancestor elements $('p').parents('.container'); // Get matching ancestor elements $('p').closest('.container'); // Get closest matching ancestor // Sibling elements $('p').next(); // Next sibling element $('p').prev(); // Previous sibling element $('p').nextAll(); // All following sibling elements $('p').prevAll(); // All preceding sibling elements $('p').siblings(); // All sibling elements $('p').siblings('.active'); // Matching sibling elements

5. DOM Insertion

javascript
// Internal insertion $('div').append('<p>New paragraph</p>'); // Insert at end of element $('<p>New</p>').appendTo('div'); // Insert at end of element $('div').prepend('<p>New paragraph</p>'); // Insert at beginning of element $('<p>New</p>').prependTo('div'); // Insert at beginning of element // External insertion $('div').after('<p>New paragraph</p>'); // Insert after element $('<p>New</p>').insertAfter('div'); // Insert after element $('div').before('<p>New paragraph</p>'); // Insert before element $('<p>New</p>').insertBefore('div'); // Insert before element // Replace $('p').replaceWith('<div>New</div>'); // Replace element $('<div>New</div>').replaceAll('p'); // Replace all matched elements

6. DOM Deletion

javascript
// Delete elements $('p').remove(); // Delete matched elements and their children $('p').empty(); // Empty element content, keep element itself // Detach elements const $detached = $('p').detach(); // Delete element but keep data and events

7. DOM Copying

javascript
// Clone element const $clone = $('div').clone(); // Clone element const $cloneWithEvents = $('div').clone(true); // Clone element and copy events

8. Element Filtering

javascript
// Filter elements $('li').filter('.active'); // Keep matching elements $('li').not('.active'); // Remove matching elements $('li').first(); // Get first element $('li').last(); // Get last element $('li').eq(2); // Get element with index 2 $('li').slice(1, 4); // Get elements with indices 1-3 // Find elements $('div').has('p'); // Div containing p $('div').is('.active'); // Check if matches

9. Collection Operations

javascript
// Get element count $('li').length; // Or $('li').size() // Get index $('li').index(); // Index of current element in collection $('li').index($('.active')); // Index of specified element // Convert to array const texts = $('li').map(function() { return $(this).text(); }).get(); // Convert to regular array // Iterate elements $('li').each(function(i, elem) { console.log(i, $(this).text()); }); // Get DOM element const elem = $('div')[0]; // Get first native DOM element const elem = $('div').get(0); // Same as above const elems = $('div').get(); // Get all native DOM elements

10. Practical Examples

javascript
// Extract article titles and links const articles = []; $('.article').each(function() { articles.push({ title: $(this).find('h2').text(), link: $(this).find('a').attr('href'), summary: $(this).find('p').text().trim() }); }); // Modify table data $('table tr').each(function() { const $row = $(this); const price = parseFloat($row.find('.price').text()); if (price > 100) { $row.addClass('highlight'); } }); // Generate new HTML const $container = cheerio.load('<div class="container"></div>'); data.items.forEach(item => { $container('.container').append(` <div class="item"> <h3>${item.title}</h3> <p>${item.description}</p> </div> `); });
标签:NodeJSCheerio