// By IDconstelement=document.getElementById('content');// By class (returns NodeList)constelements=document.getElementsByClassName('my-class');// By tag (returns HTMLCollection)constdivs=document.getElementsByTagName('div');// Modern selectors (returns first match)constelement=document.querySelector('#content p.intro');// Returns NodeList of all matchesconstelements=document.querySelectorAll('.items');
2. Modifying Content
// Replace all content (parses HTML)element.innerHTML='<strong>New content</strong>';// Just text (safer against XSS)element.textContent='Plain text content';// For form elementsinputElement.value='New value';
3. Creating and Adding Elements
// Create new elementconstnewParagraph=document.createElement('p');newParagraph.textContent='A new paragraph';// Append to endcontentDiv.appendChild(newParagraph);// Insert before another elementcontentDiv.insertBefore(newParagraph,existingElement);// Insert adjacent HTML (more flexible)contentDiv.insertAdjacentHTML('beforeend','<p>New paragraph</p>');// Positions: 'beforebegin', 'afterbegin', 'beforeend', 'afterend'
4. Best Practice Example
// Instead of innerHTML (which can have security risks), you can:constcontentDiv=document.getElementById('content');// Clear existing contentwhile (contentDiv.firstChild){contentDiv.removeChild(contentDiv.firstChild);}// Create and append new elementsconstheading=document.createElement('h2');heading.textContent='Section Title';contentDiv.appendChild(heading);constparagraph=document.createElement('p');paragraph.textContent='This is a paragraph of text.';contentDiv.appendChild(paragraph);
5. Event Handling
contentDiv.addEventListener('click',function(event){console.log('Div was clicked!',event);});
Super handy refresher! I always come back to these basics when building anything serious. Any plans to cover reactive or AI-powered DOM approaches next?
Maybe in the future, it depends, I write posts when there is a need, like this post .
I just haven't coded any JS for like three months or so and I forgot the basics , made a refresher with help of AI and noticed that it did really remind me of the basic, so I just posted it 🤷♂️ , I'm actually surprised that someone read it
Top comments (4)
Super handy refresher! I always come back to these basics when building anything serious. Any plans to cover reactive or AI-powered DOM approaches next?
Maybe in the future, it depends, I write posts when there is a need, like this post .
I just haven't coded any JS for like three months or so and I forgot the basics , made a refresher with help of AI and noticed that it did really remind me of the basic, so I just posted it 🤷♂️ , I'm actually surprised that someone read it
Pretty cool, I always need a refresher like this when my brain blanks on the basics
Some comments may only be visible to logged-in visitors. Sign in to view all comments.