Page 184 - Web_Application_v2.0_C12_Fb
P. 184

  querySelector: Accesses the first element that matches a specified CSS selector.
                 const element = document.querySelector('.myClassName');
                querySelectorAll: Accesses all elements that match a specified CSS selector (returns a NodeList).

                 const elements = document.querySelectorAll('div.myClassName');

              Modifying Elements

              After accessing an element, you can change its properties. Here are some common tasks:"
                Modifying Text Content: Updates the text inside an HTML element using JavaScript.
                 const element = document.getElementById('myElementId');
                element.textContent = 'New Text Content';

                Modifying HTML Content: Replaces the inner HTML of an element with new HTML markup.

                 const element = document.getElementById('myElementId');
                element.innerHTML = '<strong>Bold Text</strong>';
                Modifying Styles: Modifies the CSS properties of an element to change its appearance.

                 const element = document.getElementById('myElementId');
                element.style.color = 'blue';
                element.style.fontSize = '20px';

              Adding and Removing Elements
              You can also add or remove elements from the DOM. Some tasks are as follows:

                Creating and Appending New Elements: Generates new HTML elements dynamically and adds them to
                 the document.

                const newElement = document.createElement('div');
                newElement.textContent = 'I am a new div';
                document.body.appendChild(newElement);
                Deleting an Element: Deletes an existing HTML element from the DOM.
                const element = document.getElementById('myElementId');

                element.parentNode.removeChild(element);
              Example 2: To interact with HTML Web page using DOM functions

                  <!DOCTYPE HTML>
                  <HTML>
                  <HEAD>
                  <TITLE>DOM Interaction Example</TITLE>

                  </HEAD>
                  <BODY>
                  <H1 ID="TITLE">Hello, World!</H1>
                  <BUTTON ID="CHANGETEXT">Change Text</BUTTON>

                  <BUTTON ID="ADDDIV">Add Div</BUTTON>
                  <DIV ID="CONTAINER"></DIV>
                  <SCRIPT>

                182   Touchpad Web Applications (Ver. 2.0)-XII
   179   180   181   182   183   184   185   186   187   188   189