-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathCh 7 DOM Practice Set.js
68 lines (39 loc) · 2.12 KB
/
Ch 7 DOM Practice Set.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// Ch 7 DOM Practice Set
// Q1: How can you access an HTML element by its unique ID?
// A: By using the getElementById method. For example:
const element = document.getElementById('myElement');
// Q2: How can you access HTML elements based on their class name?
// A: By using the getElementsByClassName method. For example:
const elements = document.getElementsByClassName('myClass');
// Q3: How can you access HTML elements based on their tag name?
// A: By using the getElementsByTagName method. For example:
const elements = document.getElementsByTagName('h1');
// Q4: How can you access HTML elements using CSS selectors?
// A: By using the querySelector method. For example:
const element = document.querySelector('.mySelector');
// Q5: How can you modify the content of an HTML element?
// A: By using the innerHTML property. For example:
const myDiv = document.getElementById('myDiv');
myDiv.innerHTML = 'Hello, JavaScript!';
// Q6: How can you modify the attributes of an HTML element?
// A: By using the setAttribute method. For example:
const myImage = document.getElementById('myImage');
myImage.setAttribute('src', 'new_image.jpg');
// Q7: How can you modify the styles of an HTML element?
// A: By using the style property. For example:
const myDiv = document.getElementById('myDiv');
myDiv.style.backgroundColor = 'red';
// Q8: How can you add a class to an HTML element?
// A: By using the classList.add method. For example:
const myDiv = document.getElementById('myDiv');
myDiv.classList.add('highlight');
// Q9: How can you create a new HTML element and append it to the document?
// A: By using the createElement and appendChild methods. For example:
const newParagraph = document.createElement('p');
newParagraph.innerHTML = 'This is a new paragraph.';
document.body.appendChild(newParagraph);
// Q10: How can you check if an element contains another element as a descendant?
// A: By using the contains method. For example:
const parentElement = document.getElementById('parent');
const childElement = document.getElementById('child');
const isChildOfParent = parentElement.contains(childElement);