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