JavaScript DOM manipulation tutorial with dynamic web elements
DOM Manipulation in JavaScript: Building Interactive and Dynamic Web Applications

Introduction to the DOM (Document Object Model)

Welcome to Day 15 of our 30-day JavaScript and Node.js learning series! Previously, we discussed about the event loop in JavaScript. Today, we’ll explore the essential concept of DOM manipulation in JavaScript, a skill that forms the foundation of interactive web development.

The Document Object Model (DOM) is a fundamental concept in web development. It represents the structure of an HTML or XML document as a tree of nodes, allowing JavaScript to interact with and manipulate the document’s elements.

Understanding the DOM Tree

The DOM tree is a hierarchical structure where each node represents an element, attribute, or text content.

  • Nodes: The building blocks of the DOM.
    • Element Nodes: Represent HTML elements like <div><p>, and <button>.
    • Text Nodes: Represent text content within elements.
    • Attribute Nodes: Represent attributes of elements, such as idclass, and style.
  • Parent and Child Nodes: Nodes can have parent-child relationships. The root node is the parent of all other nodes.
  • Sibling Nodes: Nodes that share the same parent are called sibling nodes.

Manipulating the DOM with JavaScript

JavaScript provides a rich set of methods for DOM manipulation in JavaScript. These allow you to select elements, change their content, and dynamically interact with your web page to enhance user experience.

Selecting Elements:

  • getElementById(): Selects an element by its ID.
const elementById = document.getElementById('myElement');
  • getElementsByTagName(): Selects elements by their tag name.
const paragraphs = document.getElementsByTagName('p');
  • getElementsByClassName(): Selects elements by their class name.
const listItems = document.getElementsByClassName('list-item')
  • querySelector(): Selects the first element that matches a CSS selector.
const firstParagraph = document.querySelector('p');
  • querySelectorAll(): Selects all elements that match a CSS selector.
const allParagraphs = document.querySelectorAll('p');

Modifying Element Content and Attributes:

  • textContent: Sets or gets the text content of an element.
  • innerHTML: Sets or gets the HTML content of an element.
  • setAttribute(): Sets the value of an attribute.
  • getAttribute(): Gets the value of an attribute.
  • removeAttribute(): Removes an attribute.

Creating and Removing Elements:

  • createElement(): Creates a new element.
  • appendChild(): Adds a child element to a parent element.
  • removeChild(): Removes a child element from a parent element.

Styling Elements with JavaScript:

  • style property: Directly modifies the style properties of an element.
  • CSSOM: A programming interface for manipulating CSS styles.

DOM Events

DOM events are triggered by user interactions or changes in the DOM. By handling these events, you can create dynamic and interactive web applications.

Common DOM Events:

  1. click
    • Trigger: Occurs when a user clicks on an element.
    • Use Cases:
      • Submitting forms
      • Toggling elements (e.g., showing/hiding content)
      • Triggering animations or transitions
const button = document.getElementById('myButton');
button.addEventListener('click', () => {
  console.log('Button clicked!');
});
  1. mouseover
  2. mouseout
    • Trigger:
      • mouseover: Occurs when the mouse pointer moves over an element.
      • mouseout: Occurs when the mouse pointer moves away from an element.
    • Use Cases:
      • Creating tooltips or popups
      • Highlighting elements on hover
      • Triggering animations on hover
const element = document.getElementById('myElement');
element.addEventListener('mouseover', () => {
  element.style.backgroundColor = 'yellow';
});
element.addEventListener('mouseout', () => {
  element.style.backgroundColor = 'white';
});
  1. keydown: Occurs when a key is pressed.
  2. keyup: Occurs when a key is released.
    • Trigger:
      • keydown: Occurs when a key is pressed.
      • keyup: Occurs when a key is released.
    • Use Cases:
      • Creating keyboard shortcuts
      • Real-time search and filtering
      • Game development
document.addEventListener('keydown', (event) => {
  if (event.key === 'Enter') {
    console.log('Enter key pressed');
  }
});
  1. Focus and Blur Event
    • Trigger:
      • focus: Occurs when an element gains focus (e.g., when a user clicks on an input field).
      • blur: Occurs when an element loses focus.
    • Use Cases:
      • Validating input fields
      • Displaying tooltips or hints
      • Auto-completing forms
const input = document.getElementById('myInput');
input.addEventListener('focus', () => {
  input.style.borderColor = 'blue';
});
input.addEventListener('blur', () => {
  input.style.borderColor = 'gray';
});
  1. submit: Occurs when a form is submitted.
    • Trigger: Occurs when a form is submitted.
    • Use Cases:
      • Handling form submissions without page refreshes.
      • Validating form data before submission.
      • Sending form data to a server using AJAX.
<form id="myForm">
  <input type="text" id="name">
  <button type="submit">Submit</button>
</form>

<script>
  const form = document.getElementById('myForm');
  form.addEventListener('submit', (event) => {
    event.preventDefault(); // Prevent default form submission
    const name = document.getElementById('name').value;
    // Process the form data, e.g., send it to a server
    console.log('Form submitted:', name);
  });
</script>
  1. resize: Occurs when the browser window is resized.
    • Trigger: Occurs when the browser window is resized.
    • Use cases:
      • Responsive design: Adjusting layout and content based on screen size.
      • Dynamic resizing of elements: Resizing images, charts, or other elements to fit the viewport.
      • Repositioning elements: Moving elements around the page to maintain optimal layout.
window.addEventListener('resize', () => {
  console.log('Window resized!');
  // Adjust layout or element styles based on window size
});
  1. scroll: Occurs when the user scrolls the page.
    • Trigger: Occurs when the user scrolls the page.
    • Use Cases:
      • Lazy loading: Loading images or content only when they are about to enter the viewport.
      • Infinite scrolling: Fetching more content as the user scrolls to the bottom of the page.
      • Sticky headers and footers: Keeping elements fixed to the top or bottom of the viewport.
window.addEventListener('scroll', () => {
  const scrollY = window.scrollY;
  if (scrollY > 100) {
    document.body.classList.add('scrolled');
  } else {
    document.body.classList.remove('scrolled');
  }
});

Event Listeners and Handlers:

  • addEventListener(): Attaches an event listener to an element.
  • removeEventListener(): Removes an event listener from an element.   
  • Event handlers are functions that are executed when an event occurs.

Advanced DOM Techniques

  • DOM Traversal: Navigate the DOM tree using methods like parentNodechildNodesfirstChildlastChildnextSibling, and previousSibling.
  • DOM MutationObserver: Monitor changes to the DOM and trigger custom events.
  • Web Components: Create reusable custom elements with their own HTML, CSS, and JavaScript.
  • Shadow DOM: Encapsulate parts of the DOM to create isolated components with their own styles and scripts.

Real-World Example: Creating a Dynamic To-Do List

Let’s create a simple to-do list application using DOM manipulation in JavaScript. This example will show you how to add, remove, and update list items dynamically, making your web applications more engaging.

  1. HTML Structure:
<!DOCTYPE html>
<html>
<head>
    <title>To-Do List</title>
    <style>
        .completed {
            text-decoration: line-through;
            color: gray;
        }
    </style>
</head>
<body>
    <input type="text" id="todo-input">
    <button id="add-todo">Add Todo</button>
    <button id="clear-all">Clear All</button>
    <ul id="todo-list"></ul>
    <script src="script.js"></script>
</body>
</html>
  1. JavaScript Code:
const input = document.getElementById('todo-input');
const addButton = document.getElementById('add-todo');
const todoList = document.getElementById('todo-list');
const clearButton = document.getElementById('clear-all');

addButton.addEventListener('click', () => {
    const todoText = input.value.trim();
    if (todoText) {
        const li = document.createElement('li');
        li.textContent = todoText;

        const checkbox = document.createElement('input');
        checkbox.type = 'checkbox';
        checkbox.addEventListener('change', () => {
            li.classList.toggle('completed');
        });
        li.appendChild(checkbox);

        todoList.appendChild(li);
        input.value = '';
    }
});

clearButton.addEventListener('click', () => {
    while (todoList.firstChild) {
        todoList.removeChild(todoList.firstChild);
    }
});

Let’s break down the to-do list example further to illustrate advanced DOM manipulation techniques:

  1. Dynamically Adding and Removing To-Do Items:
    • Adding a To-Do:
      1. Create a new li element using createElement().
      2. Set the text content of the li element to the user’s input.
      3. Append the new li element to the ul element using appendChild().
    • Removing a To-Do:
      1. Attach a click event listener to each li element.
      2. When an li is clicked, use parentNode to access its parent ul element.
      3. Use removeChild() to remove the clicked li from the ul.
  2. Marking To-Do Items as Complete:
    • Adding a Checkbox:
      1. Create a checkbox element for each li element.
      2. Append the checkbox to the li element.
    • Toggling the completed Class:
      1. Add a CSS class completed to style completed items.
      2. When the checkbox is checked, add the completed class to the li.
      3. When the checkbox is unchecked, remove the completed class.
  3. Clearing the To-Do List:
    • Add a “Clear All” Button:
      1. Create a button element with the text “Clear All”.
      2. Attach a click event listener to the button.
    • Clearing the List:
      1. Use a while loop to remove the first child of the ul element until it’s empty.

Best Practices for DOM Manipulation

  • Performance Optimization:
    • Minimize DOM manipulations by batching changes.
    • Use efficient selectors and avoid unnecessary DOM traversals.
  • Cross-Browser Compatibility:
    • Write code that works across different browsers and devices.
    • Use feature detection and polyfills to ensure compatibility.
  • Security Considerations:
    • Be cautious when manipulating the DOM to prevent cross-site scripting (XSS) attacks.
    • Sanitize user input and validate data to avoid security vulnerabilities.

By mastering these advanced DOM concepts, you can create sophisticated and interactive web applications that deliver exceptional user experiences.

Common Pitfalls to Avoid:

  • Inefficient DOM Manipulations: Avoid frequent DOM updates, as they can impact performance.
  • Incorrect Event Handling: Ensure correct event listeners and handlers to avoid unexpected behavior.
  • Cross-Browser Compatibility Issues: Test your code across different browsers to identify and address compatibility problems.
  • Security Vulnerabilities: Sanitize user input and validate data to prevent attacks.

Conclusion

The DOM is a cornerstone of web development, offering a powerful interface to manipulate and interact with HTML and XML documents. By understanding the DOM’s structure, properties, and methods, you can create dynamic and interactive web applications.

Key takeaways from this exploration include:

  • DOM Structure: The hierarchical nature of the DOM, comprising nodes, elements, and attributes.
  • DOM Manipulation: Techniques to select, create, modify, and remove elements.
  • DOM Events: Handling user interactions and triggering actions based on events.
  • Advanced DOM Concepts: Leveraging techniques like DOM traversal, MutationObserver, Web Components, and Shadow DOM for complex applications.
  • Best Practices: Prioritizing performance, cross-browser compatibility, and security.

By understanding DOM manipulation in JavaScript, you can unlock the full potential of JavaScript to build engaging and responsive web experiences.



Previous Lesson

Day 14: JavaScript Modules

70 Comments

  1. F*ckin’ remarkable things here. I’m very happy to look your post. Thanks a lot and i’m having a look forward to contact you. Will you please drop me a mail?

  2. This is a very good tips especially to those new to blogosphere, brief and accurate information… Thanks for sharing this one. A must read article.

  3. Thanks for sharing superb informations. Your site is very cool. I’m impressed by the details that you’ve on this website. It reveals how nicely you perceive this subject. Bookmarked this web page, will come back for more articles. You, my pal, ROCK! I found just the information I already searched everywhere and just couldn’t come across. What an ideal site.

  4. You have remarked very interesting details! ps decent web site. “I understand a fury in your words, But not the words.” by William Shakespeare.

  5. Magnificent goods from you, man. I have consider your stuff prior to and you’re just too magnificent. I actually like what you’ve obtained here, really like what you are stating and the best way by which you are saying it. You make it entertaining and you continue to take care of to keep it wise. I can’t wait to read much more from you. This is actually a tremendous web site.

  6. Whats up very nice web site!! Guy .. Beautiful .. Wonderful .. I’ll bookmark your website and take the feeds additionally…I’m happy to seek out a lot of helpful info right here within the publish, we want develop more strategies on this regard, thank you for sharing.

  7. Hi there! I know this is somewhat off topic but I was wondering which blog platform are you using for this website? I’m getting fed up of WordPress because I’ve had issues with hackers and I’m looking at alternatives for another platform. I would be fantastic if you could point me in the direction of a good platform.

  8. After study a few of the blog posts on your website now, and I truly like your way of blogging. I bookmarked it to my bookmark website list and will be checking back soon. Pls check out my web site as well and let me know what you think.

  9. I like what you guys are up too. Such intelligent work and reporting! Carry on the excellent works guys I’ve incorporated you guys to my blogroll. I think it will improve the value of my site :).

  10. Hello there! I could have sworn I’ve been to this site before but after reading through some of the post I realized it’s new to me. Nonetheless, I’m definitely happy I found it and I’ll be book-marking and checking back frequently!

  11. Hi, i feel that i noticed you visited my website so i came to “return the favor”.I’m trying to in finding things to enhance my web site!I suppose its ok to use some of your ideas!!

  12. Can I simply say what a relief to find somebody who really is aware of what theyre speaking about on the internet. You definitely know the best way to carry a difficulty to mild and make it important. Extra individuals must learn this and perceive this aspect of the story. I cant imagine youre no more fashionable since you undoubtedly have the gift.

  13. A powerful share, I simply given this onto a colleague who was doing a bit analysis on this. And he in reality bought me breakfast as a result of I discovered it for him.. smile. So let me reword that: Thnx for the deal with! However yeah Thnkx for spending the time to debate this, I really feel strongly about it and love reading more on this topic. If attainable, as you turn into experience, would you thoughts updating your blog with extra details? It’s extremely useful for me. Huge thumb up for this weblog post!

  14. You made a few fine points there. I did a search on the subject matter and found nearly all folks will agree with your blog.

  15. I just could not depart your site prior to suggesting that I really enjoyed the standard info a person provide for your visitors? Is going to be back often in order to check up on new posts

  16. I am now not sure the place you are getting your info, however good topic. I needs to spend a while studying much more or working out more. Thanks for great information I used to be on the lookout for this info for my mission.

  17. I’m still learning from you, as I’m trying to achieve my goals. I definitely love reading all that is written on your site.Keep the tips coming. I loved it!

  18. I would like to thnkx for the efforts you have put in writing this blog. I am hoping the same high-grade blog post from you in the upcoming as well. In fact your creative writing abilities has inspired me to get my own blog now. Really the blogging is spreading its wings quickly. Your write up is a good example of it.

  19. Attractive section of content. I just stumbled upon your web site and in accession capital to assert that I acquire actually enjoyed account your blog posts. Any way I will be subscribing to your augment and even I achievement you access consistently quickly.

  20. I happen to be writing to let you be aware of of the outstanding experience our child had using your web site. She figured out many issues, not to mention what it’s like to have an amazing teaching nature to make many more with no trouble fully grasp various grueling subject areas. You really surpassed her expectations. Thank you for delivering those helpful, safe, explanatory and in addition unique thoughts on your topic to Tanya.

  21. Pretty nice post. I just stumbled upon your blog and wanted to say that I have really loved browsing your blog posts. In any case I’ll be subscribing on your feed and I am hoping you write once more very soon!

  22. An interesting dialogue is price comment. I think that you need to write more on this matter, it won’t be a taboo subject however generally people are not sufficient to speak on such topics. To the next. Cheers

  23. Magnificent site. A lot of useful information here. I am sending it to some pals ans also sharing in delicious. And certainly, thank you to your sweat!

  24. I don’t even know how I ended up here, but I thought this post was great. I do not know who you are but certainly you’re going to a famous blogger if you are not already 😉 Cheers!

  25. Unquestionably imagine that that you stated. Your favorite justification appeared to be at the internet the easiest thing to understand of. I say to you, I definitely get annoyed whilst folks consider issues that they just don’t realize about. You controlled to hit the nail upon the highest and also defined out the entire thing with no need side-effects , people could take a signal. Will probably be again to get more. Thank you

  26. It’s really a nice and helpful piece of info. I am glad that you shared this useful information with us. Please keep us informed like this. Thanks for sharing.

  27. Do you have a spam issue on this website; I also am a blogger, and I was wondering your situation; many of us have created some nice methods and we are looking to exchange solutions with others, why not shoot me an e-mail if interested.

  28. Great items from you, man. I’ve consider your stuff prior to and you’re just extremely fantastic. I actually like what you have obtained here, really like what you’re stating and the way in which by which you are saying it. You’re making it enjoyable and you continue to care for to stay it sensible. I can not wait to learn far more from you. This is actually a wonderful website.

  29. Very interesting details you have mentioned, regards for putting up. “The biggest fool may come out with a bit of sense when you least expect it.” by Eden Phillpotts.

  30. Heya i’m for the first time here. I found this board and I in finding It really useful & it helped me out a lot. I hope to provide something again and aid others like you helped me.

  31. It’s the best time to make some plans for the long run and it is time to be happy. I have read this submit and if I could I desire to recommend you few fascinating issues or suggestions. Perhaps you could write next articles referring to this article. I desire to read more issues about it!

  32. I genuinely enjoy examining on this web site, it has got great blog posts. “We find comfort among those who agree with us–growth among those who don’t.” by Frank A. Clark.

  33. It’s in reality a nice and helpful piece of information. I’m glad that you simply shared this useful information with us. Please stay us informed like this. Thanks for sharing.

  34. Definitely imagine that which you said. Your favorite justification appeared to be at the net the simplest thing to take note of. I say to you, I definitely get annoyed whilst people think about worries that they just do not know about. You controlled to hit the nail upon the highest as neatly as defined out the entire thing with no need side effect , people could take a signal. Will probably be back to get more. Thank you

  35. Si eres fanatico de los juegos de azar en Espana, has llegado al portal correcto.
    En este sitio encontraras informacion detallada sobre los plataformas mas seguras disponibles en Espana.
    ### Ventajas de jugar en casinos de Espana
    – **Casinos regulados** para jugar con total confianza.
    – **Bonos de bienvenida exclusivos** que aumentan tus posibilidades de ganar.
    – **Ruleta, blackjack, tragaperras y mas** con premios atractivos.
    – **Transacciones confiables** con multiples metodos de pago, incluyendo tarjetas, PayPal y criptomonedas.
    Lista de los casinos mas recomendados
    En este portal hemos recopilado las **resenas mas completas** sobre los casinos con mejor reputacion en Espana. Consulta la informacion aqui: casinotorero.info.
    **Registrate hoy en un casino confiable y aprovecha todas las ventajas.**

  36. You have brought up a very excellent points, thanks for the post.

  37. I’m not sure why but this site is loading extremely slow for me. Is anyone else having this problem or is it a problem on my end? I’ll check back later on and see if the problem still exists.

  38. Fantastic blog! Do you have any helpful hints for aspiring writers? I’m hoping to start my own site soon but I’m a little lost on everything. Would you propose starting with a free platform like WordPress or go for a paid option? There are so many options out there that I’m totally overwhelmed .. Any recommendations? Many thanks!

  39. I will right away grab your rss feed as I can’t find your e-mail subscription link or e-newsletter service. Do you have any? Kindly let me know so that I could subscribe. Thanks.

  40. I truly enjoy reading through on this site, it contains superb blog posts. “The living is a species of the dead and not a very attractive one.” by Friedrich Wilhelm Nietzsche.

  41. It is in point of fact a nice and useful piece of info. I am satisfied that you simply shared this useful info with us. Please stay us informed like this. Thanks for sharing.

  42. Great remarkable issues here. I?¦m very satisfied to peer your post. Thank you a lot and i’m having a look ahead to contact you. Will you kindly drop me a e-mail?

  43. I have been absent for some time, but now I remember why I used to love this web site. Thank you, I?¦ll try and check back more frequently. How frequently you update your website?

  44. I’m really enjoying the theme/design of your blog. Do you ever run into any browser compatibility problems? A few of my blog audience have complained about my blog not operating correctly in Explorer but looks great in Safari. Do you have any advice to help fix this problem?

  45. Excellent website you have here but I was curious if you knew of any forums that cover the same topics discussed here? I’d really love to be a part of group where I can get comments from other knowledgeable individuals that share the same interest. If you have any suggestions, please let me know. Kudos!

  46. I have to show my affection for your kindness in support of people who really need guidance on this particular situation. Your personal commitment to passing the message all over had been surprisingly advantageous and has consistently permitted some individuals much like me to arrive at their objectives. Your entire invaluable information entails a great deal a person like me and much more to my office colleagues. Best wishes; from each one of us.

  47. Wow! Thank you! I always wanted to write on my website something like that. Can I take a portion of your post to my blog?

  48. I was looking through some of your articles on this website and I believe this website is very instructive! Keep on posting.

  49. I together with my guys appeared to be reviewing the great recommendations on your site while immediately got a horrible suspicion I had not expressed respect to you for those techniques. The young men ended up excited to read them and have now extremely been using them. We appreciate you really being quite accommodating and for having variety of fabulous areas millions of individuals are really needing to discover. My sincere regret for not saying thanks to you sooner.

  50. Hi there! I’m at work browsing your blog from my new apple iphone! Just wanted to say I love reading your blog and look forward to all your posts! Keep up the excellent work!

  51. Great wordpress blog here.. It’s hard to find quality writing like yours these days. I really appreciate people like you! take care

  52. Thanks, I’ve recently been looking for info approximately this subject for a while and yours is the best I have came upon till now. However, what about the bottom line? Are you certain in regards to the source?

Leave a Reply

Your email address will not be published. Required fields are marked *