Cheatsheet: Advanced DOM Manipulation & Web Scraping Techniques Using the Console
1. Selecting Elements
1.1 Query Selector
Selects the first match of a specified CSS selector(s).
let element = document.querySelector('.my-class');
1.2 Query Selector All
Selects all matches of a specified CSS selector(s).
let elements = document.querySelectorAll('.my-class');
1.3 Get Elements By ClassName
Selects all elements with a specific class.
let elements = document.getElementsByClassName('my-class');
1.4 Get Element By Id
Selects the element with the specified id.
let element = document.getElementById('my-id');
2. Manipulating Elements
2.1 Changing Inner HTML
Modifies the inner HTML of a selected element.
element.innerHTML = 'New Content';
2.2 Adding a Class
Adds a class to the selected element.
element.classList.add('new-class');
2.3 Removing a Class
Removes a class from the selected element.
element.classList.remove('remove-class');
2.4 Toggle a Class
Toggles a class on the selected element.
element.classList.toggle('toggle-class');
3. Web Scraping Techniques
3.1 Extracting Text Content
Extracts the text content of an element.
let text = element.textContent;
3.2 Extracting HTML Content
Extracts the HTML content of an element.
let html = element.innerHTML;
3.3 Extracting Attribute Values
Extracts the value of a specified attribute from an element.
let src = element.getAttribute('src');
3.4 Looping Over Elements
Loops over a NodeList, applying a function to each element.
elements.forEach((element) => {
console.log(element.textContent);
});
4. Feature Augmentation
4.1 Creating New Elements
Creates a new element and adds it to the DOM.
let newElement = document.createElement('div');
newElement.innerHTML = 'I am a new element';
document.body.appendChild(newElement);
4.2 Event Listeners
Attaches an event listener to an element.
element.addEventListener('click', function() {
console.log('Element clicked!');
});
4.3 Styling Elements
Applies CSS styles to an element.
element.style.color = 'blue';
element.style.fontSize = '2em';
4.4 Manipulating Attributes
Modifies the attributes of an element.
element.setAttribute('src', 'new-image.jpg');
Remember to use these techniques responsibly.