|
2 | 2 |
|
3 | 3 | //1.getElementById(id)-Selects an element by its ID |
4 | 4 |
|
5 | | -let tittle = document.getElementById('title') |
6 | | -console.log(tittle.textContent)//prints Hello World |
7 | | -tittle.style.color = "blue"//changes text to blue |
| 5 | +let title = document.getElementById('title'); |
| 6 | +console.log(title.textContent);//prints Hello World |
| 7 | +title.style.color = "blue";//changes text to blue |
8 | 8 |
|
9 | 9 |
|
10 | 10 | //2.querySelector(selector)-Selects the first element matching CSS selector |
11 | 11 |
|
12 | 12 | let paragraph = document.querySelector(".message"); |
13 | 13 | paragraph.textContent = "This text has been changed!"; |
14 | | -paragraph.style.color = "red" |
| 14 | +paragraph.style.color = "red"; |
15 | 15 |
|
| 16 | +//3.querySelectorAll(selector)-Seletcts all elements matching selector and returns an array |
| 17 | +let allParagraphs = document.querySelectorAll("p"); |
| 18 | +allParagraphs.forEach(function(paragraph) { |
| 19 | + paragraph.style.fontSize = "18px"; |
| 20 | +}); |
16 | 21 |
|
17 | | -//3.addEventListener()-Attaches an event (like a click) to an element. |
| 22 | +//4.addEventListener()-Attaches an event (like a click) to an element. |
18 | 23 |
|
19 | 24 | let button = document.getElementById('myBtn'); |
20 | 25 | button.addEventListener("click", |
21 | 26 | function () { |
22 | 27 | alert("Button clicked") |
23 | 28 | } |
24 | | -) |
| 29 | +); |
25 | 30 |
|
26 | | -//4.removeChild()-Removes a child element from a parent. |
| 31 | +//5.removeChild()-Removes a child element from a parent. |
27 | 32 | let list = document.getElementById("list"); |
28 | 33 | let firstItem = list.firstElementChild; |
29 | 34 | list.removeChild(firstItem); // removes "Item 1" |
30 | 35 |
|
| 36 | +//6.appendChild()-Adds a new child element to a parent. |
| 37 | +let newItem = document.createElement("li"); |
| 38 | +newItem.textContent = "Item 3"; |
| 39 | +list.appendChild(newItem); |
31 | 40 |
|
32 | | - |
33 | | - |
34 | | - |
35 | | - |
36 | | - |
37 | | - |
38 | | - |
39 | | - |
40 | | - |
| 41 | +//7.replaceChild()-Replaces an existing child element with a new one. |
| 42 | +let secondItem = list.children[1]; |
| 43 | +let newItem2 = document.createElement("li"); |
| 44 | +newItem2.textContent = "Item 5"; |
| 45 | +list.replaceChild(newItem2, secondItem); |
41 | 46 |
|
0 commit comments