1. FINDING ELEMENTS (What to Use When)
// MODERN WAY (Use These 90% of Time)
document.querySelector('#myId') // ONE element by ID
document.querySelector('.myClass') // ONE element by class
document.querySelector('div') // ONE element by tag
document.querySelector('div.active') // Combined selectors
document.querySelectorAll('.myClass') // ALL elements by class
document.querySelectorAll('div > p') // ALL with complex selectors
// OLD WAY (Still Works, Sometimes Faster)
document.getElementById('myId') // Just pass "myId", no #
document.getElementsByClassName('myClass') // Just pass "myClass", no .
document.getElementsByTagName('div') // Just pass "div"Remember:
querySelector= CSS syntax (.class,#id)getElementBy= plain strings ("class","id")
2. COLLECTIONS vs ELEMENTS - What You Get Back
// SINGLE ELEMENT (can use directly)
let elem = document.querySelector('.btn');
elem.style.color = 'red'; // ✅ Works
// COLLECTION (need to loop or pick index)
let elems = document.querySelectorAll('.btn');
elems.style.color = 'red'; // ❌ Won't work!
// Convert to real array for array methods
Array.from(elems).forEach(el => el.style.color = 'red'); // ✅
[...elems].forEach(el => el.style.color = 'red'); // ✅
// Or just loop directly (collections are iterable)
for (let el of elems) el.style.color = 'red'; // ✅ Easiest3. NAVIGATING DOM TREE
// PARENT/CHILD NAVIGATION
elem.parentElement // Go up one level
elem.children // All child elements (no text nodes)
elem.childNodes // All children (includes text nodes)
elem.firstElementChild // First child element
elem.lastElementChild // Last child element
// SIBLING NAVIGATION
elem.nextElementSibling // Next sibling element
elem.previousElementSibling // Previous sibling element
// MOST USED FOR MACHINE CODING
elem.children[0] // First child
elem.children[elem.children.length - 1] // Last childPro Tip: Use children not childNodes (avoids text node confusion)
4. READING vs WRITING CONTENT
// READING TEXT/HTML
elem.textContent // Plain text only
elem.innerHTML // HTML markup included
elem.value // For inputs, selects, textareas
// WRITING TEXT/HTML
elem.textContent = 'Plain text'; // Safe, no HTML
elem.innerHTML = '<b>Bold text</b>'; // Can inject HTML
elem.value = 'New input value'; // For form elements
// ATTRIBUTES
elem.getAttribute('data-id') // Get custom attribute
elem.setAttribute('data-id', '123') // Set custom attribute
elem.id = 'newId'; // Direct property access
elem.className = 'new-class'; // Set class (overwrites)
elem.classList.add('new-class'); // Add class (keeps existing)5. STYLING ELEMENTS
// INLINE STYLES (most common in machine coding)
elem.style.color = 'red';
elem.style.backgroundColor = 'blue'; // camelCase for CSS properties
elem.style.display = 'none'; // Hide element
elem.style.display = 'block'; // Show element
// CSS CLASSES (cleaner approach)
elem.classList.add('active'); // Add class
elem.classList.remove('active'); // Remove class
elem.classList.toggle('active'); // Toggle class
elem.classList.contains('active'); // Check if has class6. FORM INPUT HANDLING
// GET INPUT VALUES
let textInput = document.querySelector('input[type="text"]');
let value = textInput.value;
let checkbox = document.querySelector('input[type="checkbox"]');
let isChecked = checkbox.checked;
let select = document.querySelector('select');
let selectedValue = select.value;
// CLEAR INPUTS
textInput.value = ''; // Clear text input
checkbox.checked = false; // Uncheck checkbox
select.selectedIndex = 0; // Reset select to first option
// CLEAR ALL INPUTS IN A FORM
let form = document.querySelector('form');
form.reset(); // Clears everything at once7. MACHINE CODING ROUND PATTERNS
// PATTERN 1: Toggle visibility
function toggleElement(selector) {
let elem = document.querySelector(selector);
elem.style.display = elem.style.display === 'none' ? 'block' : 'none';
}
// PATTERN 2: Add/remove from list
function addToList(listSelector, text) {
let list = document.querySelector(listSelector);
let item = document.createElement('li');
item.textContent = text;
list.appendChild(item);
}
// PATTERN 3: Filter/search
function filterItems(inputSelector, itemSelector) {
let searchText = document.querySelector(inputSelector).value.toLowerCase();
let items = document.querySelectorAll(itemSelector);
for (let item of items) {
let text = item.textContent.toLowerCase();
item.style.display = text.includes(searchText) ? 'block' : 'none';
}
}
// PATTERN 4: Form validation
function validateForm(formSelector) {
let inputs = document.querySelectorAll(`${formSelector} input[required]`);
return [...inputs].every(input => input.value.trim() !== '');
}8. MACHINE CODING QUICK REFERENCE
Most Used Methods:
querySelector()/querySelectorAll()- Finding elementsaddEventListener()- Event handlingstyle.property = value- StylingtextContent/innerHTML- Contentvalue- Form inputsclassList.add/remove/toggle()- CSS classesappendChild()/createElement()- Adding elements
Common Tasks & Solutions:
- Show/Hide:
elem.style.display = 'none'/'block' - Add CSS:
elem.classList.add('className') - Get Input:
input.value - Clear Input:
input.value = '' - Loop Elements:
for (let el of elements) - Check if Empty:
input.value.trim() === ''
This covers 90% of what you’ll need in machine coding rounds!
1. CREATING NEW ELEMENTS
javascript
// CREATE ELEMENTS
let div = document.createElement('div'); // Most common
let span = document.createElement('span');
let button = document.createElement('button');
// CREATE TEXT (rarely used - just set textContent instead)
let textNode = document.createTextNode('Hello'); // Almost never needed
// CLONE EXISTING ELEMENTS
let original = document.querySelector('.card');
let copy = original.cloneNode(true); // true = deep copy (includes children)
let shallow = original.cloneNode(false); // false = just the element2. MODERN INSERTION METHODS (Use These!)
javascript
let parent = document.querySelector('.container');
let newDiv = document.createElement('div');
// INSERT INSIDE PARENT
parent.append(newDiv); // Add to end of parent
parent.prepend(newDiv); // Add to beginning of parent
// INSERT RELATIVE TO ELEMENT
let targetElem = document.querySelector('.target');
targetElem.before(newDiv); // Insert before target
targetElem.after(newDiv); // Insert after target
targetElem.replaceWith(newDiv); // Replace target with new element
// REMOVE ELEMENT
targetElem.remove(); // Delete the elementThese methods can take multiple elements or strings:
javascript
parent.append(elem1, elem2, 'some text'); // Multiple at once3. OLD SCHOOL METHODS (Still Work, But Verbose)
javascript
let parent = document.querySelector('.container');
let child = document.createElement('div');
// OLD WAY (more code, same result)
parent.appendChild(child); // Same as parent.append(child)
parent.insertBefore(child, parent.firstChild); // Same as parent.prepend(child)
parent.removeChild(child); // Same as child.remove()
parent.replaceChild(newChild, oldChild); // Same as oldChild.replaceWith(newChild)When to use old methods: Legacy codebases or when you need the return value (they return the inserted node).
4. INSERT HTML STRINGS (Super Useful for Machine Coding!)
javascript
let elem = document.querySelector('.target');
// INSERT HTML STRINGS (most practical for machine coding)
elem.insertAdjacentHTML('beforebegin', '<div>Before element</div>');
elem.insertAdjacentHTML('afterbegin', '<p>Start of element</p>');
elem.insertAdjacentHTML('beforeend', '<p>End of element</p>');
elem.insertAdjacentHTML('afterend', '<div>After element</div>');
// VISUAL GUIDE:
// <div>Before element</div> ← beforebegin
// <div class="target">
// <p>Start of element</p> ← afterbegin
// [existing content]
// <p>End of element</p> ← beforeend
// </div>
// <div>After element</div> ← afterendRarely used alternatives:
javascript
elem.insertAdjacentText('beforeend', 'plain text');
elem.insertAdjacentElement('beforeend', newElement);5. MACHINE CODING PATTERNS
javascript
// PATTERN 1: Create and add list item
function addListItem(listSelector, text) {
let list = document.querySelector(listSelector);
let item = document.createElement('li');
item.textContent = text;
list.append(item); // Modern way
}
// PATTERN 2: Add HTML with event handlers
function addCard(title, content) {
let container = document.querySelector('.cards');
container.insertAdjacentHTML('beforeend', `
<div class="card">
<h3>${title}</h3>
<p>${content}</p>
<button onclick="removeCard(this)">Delete</button>
</div>
`);
}
// PATTERN 3: Replace content entirely
function updateSection(newContent) {
let section = document.querySelector('.content');
section.innerHTML = ''; // Clear first
section.insertAdjacentHTML('afterbegin', newContent);
}
// PATTERN 4: Clone and modify
function duplicateCard(cardSelector) {
let original = document.querySelector(cardSelector);
let copy = original.cloneNode(true);
copy.querySelector('.title').textContent += ' (Copy)';
original.after(copy);
}6. QUICK DECISION GUIDE
For Machine Coding, Use:
| Task | Method | Example |
|---|---|---|
| Add element to end | parent.append(elem) | list.append(newItem) |
| Add element to start | parent.prepend(elem) | list.prepend(newItem) |
| Add HTML string | elem.insertAdjacentHTML() | div.insertAdjacentHTML('beforeend', '<p>Hi</p>') |
| Remove element | elem.remove() | button.remove() |
| Replace element | elem.replaceWith(newElem) | oldDiv.replaceWith(newDiv) |
| Clone element | elem.cloneNode(true) | template.cloneNode(true) |
Key Differences:
- Elements vs Nodes: In practice, same thing for machine coding
- Modern vs Old: Modern methods are shorter and can take multiple arguments
- String vs Element:
insertAdjacentHTML()for HTML strings,append()for elements
Bottom Line: Use modern methods (append, prepend, before, after, remove) for elements, and insertAdjacentHTML() for HTML strings. These cover 95% of machine coding scenarios!
