Mastering JavaScript: Selecting Page Elements Free PDF guide Learn JavaScript Quiz and Exercises

Mastering JavaScript: Selecting Page Elements

  • Selecting by ID: Use getElementById to target specific elements by their unique identifier.
  • Selecting by Class Name: Employ getElementsByClassName to select elements based on their shared class.
  • Selecting by Tag Name: Utilize getElementsByTagName to target elements by their tag name.
  • Selecting by CSS Selectors: Leverage querySelector and querySelectorAll to select elements using CSS selectors.
  • Selecting by Attribute: Use querySelector to select elements based on their attributes.
  • Understanding these methods is crucial for dynamic web development and manipulation of the Document Object Model (DOM). 

Selecting page elements in JavaScript is a fundamental skill that allows you to interact with and manipulate the content of a webpage. To select elements, you can use various methods provided by the Document Object Model (DOM). The DOM represents the structure of a document as a tree of objects, where each object corresponds to a part of the document, such as elements, attributes, and text.

Here’s a detailed explanation along with coding examples for selecting page elements in JavaScript:

1. Selecting by ID:

To select an element by its ID, use the getElementById method.

<div id=”myElement”>Hello, World!</div>

// Selecting by ID

var elementById = document.getElementById(‘myElement’);

console.log(elementById.innerHTML); // Outputs: Hello, World!

2. Selecting by Class Name:

To select elements by their class name, use the getElementsByClassName method.

<p class=”paragraph”>This is a paragraph.</p>

<p class=”paragraph”>Another paragraph.</p>

// Selecting by Class Name

var elementsByClass = document.getElementsByClassName(‘paragraph’);

console.log(elementsByClass[0].innerHTML); // Outputs: This is a paragraph.

3. Selecting by Tag Name:

To select elements by their tag name, use the getElementsByTagName method.

<ul>

 <li>Item 1</li>

 <li>Item 2</li>

</ul>

// Selecting by Tag Name

var elementsByTag = document.getElementsByTagName(‘li’);

console.log(elementsByTag[1].innerHTML); // Outputs: Item 2

4. Selecting by CSS Selectors:

You can use the querySelector and querySelectorAll methods to select elements using CSS selectors.

<div class=”container”>

 <p id=”para1″>Paragraph 1</p>

 <p class=”paragraph”>Paragraph 2</p>

</div>

// Selecting by CSS Selectors

var container = document.querySelector(‘.container’);

var paraById = container.querySelector(‘#para1’);

var paragraphs = container.querySelectorAll(‘.paragraph’);

console.log(paraById.innerHTML); // Outputs: Paragraph 1

console.log(paragraphs[1].innerHTML); // Outputs: Paragraph 2

5. Selecting by Attribute:

You can select elements based on their attributes using the querySelector method.

<input type=”text” id=”username” name=”username”>

// Selecting by Attribute

var inputElement = document.querySelector(‘input[name=”username”]’);

console.log(inputElement.id); // Outputs: username

These are basic examples, and there are many more methods and techniques for selecting page elements in JavaScript. Understanding these concepts is crucial for dynamic web development and manipulation of the DOM.

Coding Exercises

Exercise 1: Select Element by ID

Task: Select the element with the ID “myElement” and change its text content to “New Content”.

Solution:

<!DOCTYPE html>

<html lang=”en”>

<head>

 <meta charset=”UTF-8″>

 <title>Exercise 1</title>

</head>

<body>

<div id=”myElement”>Hello, World!</div>

<script>

 // Exercise 1 Solution

 var elementById = document.getElementById(‘myElement’);

 elementById.textContent = “New Content”;

</script>

</body>

</html>

Exercise 2: Select Elements by Class Name

Task: Select all elements with the class “paragraph” and log their text content.

Solution:

<!DOCTYPE html>

<html lang=”en”>

<head>

 <meta charset=”UTF-8″>

 <title>Exercise 2</title>

</head>

<body>

<p class=”paragraph”>This is a paragraph.</p>

<p class=”paragraph”>Another paragraph.</p>

<script>

 // Exercise 2 Solution

 var elementsByClass = document.getElementsByClassName(‘paragraph’);

 for (var i = 0; i < elementsByClass.length; i++) {

 console.log(elementsByClass[i].textContent);

 }

</script>

</body>

</html>

Exercise 3: Select Elements by Tag Name

Task: Select all li elements within the ul and log their text content.

Solution:

<!DOCTYPE html>

<html lang=”en”>

<head>

 <meta charset=”UTF-8″>

 <title>Exercise 3</title>

</head>

<body>

<ul>

 <li>Item 1</li>

 <li>Item 2</li>

</ul>

<script>

 // Exercise 3 Solution

 var elementsByTag = document.getElementsByTagName(‘li’);

 for (var i = 0; i < elementsByTag.length; i++) {

 console.log(elementsByTag[i].textContent);

 }

</script>

</body>

</html>

Exercise 4: Select by CSS Selector

Task: Select the element with the class “container” and change the background color to light blue.

Solution:

<!DOCTYPE html>

<html lang=”en”>

<head>

 <meta charset=”UTF-8″>

 <title>Exercise 4</title>

</head>

<body>

<div class=”container”>

 <p id=”para1″>Paragraph 1</p>

 <p class=”paragraph”>Paragraph 2</p>

</div>

<script>

 // Exercise 4 Solution

 var container = document.querySelector(‘.container’);

 container.style.backgroundColor = ‘lightblue’;

</script>

</body>

</html>

Exercise 5: Select by Attribute

Task: Select the input element with the attribute type=”text” and log its ID.

Solution:

<!DOCTYPE html>

<html lang=”en”>

<head>

 <meta charset=”UTF-8″>

 <title>Exercise 5</title>

</head>

<body>

<input type=”text” id=”username” name=”username”>

<script>

 // Exercise 5 Solution

 var inputElement = document.querySelector(‘input[type=”text”]’);

 console.log(inputElement.id);

</script>

</body>

</html>

Exercise 6: Select Nested Elements

Task: Select all paragraphs inside the div with the class “nested” and log their text content.

Solution:

<!DOCTYPE html>

<html lang=”en”>

<head>

 <meta charset=”UTF-8″>

 <title>Exercise 6</title>

</head>

<body>

<div class=”nested”>

 <p>Paragraph 1</p>

 <p>Paragraph 2</p>

</div>

<script>

 // Exercise 6 Solution

 var nestedDiv = document.querySelector(‘.nested’);

 var nestedParagraphs = nestedDiv.querySelectorAll(‘p’);

 for (var i = 0; i < nestedParagraphs.length; i++) {

 console.log(nestedParagraphs[i].textContent);

 }

</script>

</body>

</html>

Exercise 7: Select Parent Element

Task: Select the parent element of the element with ID “childElement” and log its class.

Solution:

<!DOCTYPE html>

<html lang=”en”>

<head>

 <meta charset=”UTF-8″>

 <title>Exercise 7</title>

</head>

<body>

<div class=”parent”>

 <p id=”childElement”>Child Element</p>

</div>

<script>

 // Exercise 7 Solution

 var childElement = document.getElementById(‘childElement’);

 var parentElement = childElement.parentElement;

 console.log(parentElement.className);

</script>

</body>

</html>

Exercise 8: Select Siblings

Task: Select all sibling elements of the element with ID “targetElement” and log their text content.

Solution:

<!DOCTYPE html>

<html lang=”en”>

<head>

 <meta charset=”UTF-8″>

 <title>Exercise 8</title>

</head>

<body>

<div class=”sibling”>Sibling 1</div>

<p id=”targetElement”>Target Element</p>

<div class=”sibling”>Sibling 2</div>

<script>

 // Exercise 8 Solution

 var targetElement = document.getElementById(‘targetElement’);

 var siblings = Array.from(targetElement.parentElement.children).filter(function (el) {

 return el !== targetElement;

 });

 siblings.forEach(function (sibling) {

 console.log(sibling.textContent);

 });

</script>

</body>

</html>

Exercise 9: Select by Data Attribute

Task: Select all elements with the data attribute data-role=”section” and log their text content.

Solution:

<!DOCTYPE html>

<html lang=”en”>

<head>

 <meta charset=”UTF-8″>

 <title>Exercise 9</title>

</head>

<body>

<div data-role=”section”>Section 1</div>

<div data-role=”section”>Section 2</div>

<script>

 // Exercise 9 Solution

 var sections = document.querySelectorAll(‘[data-role=”section”]’);

 sections.forEach(function (section) {

 console.log(section.textContent);

 });

</script>

</body>

</html>

Exercise 10: Select by nth-child

Task: Select the third li element within the ul and change its font color to red.

Solution:

<!DOCTYPE html>

<html lang=”en”>

<head>

 <meta charset=”UTF-8″>

 <title>Exercise 10</title>

 <style>

 ul li {

 color: black;

 }

 </style>

</head>

<body>

<ul>

 <li>Item 1</li>

 <li>Item 2</li>

 <li>Item 3</li>

</ul>

<script>

 // Exercise 10 Solution

 var thirdLi = document.querySelector(‘ul li:nth-child(3)’);

 thirdLi.style.color = ‘red’;

</script>

</body>

</html>

These exercises cover various scenarios for selecting page elements using different methods and techniques in JavaScript. They should provide a solid foundation for working with the DOM in web development.

Quiz Questions

Question: How do you select an element by its ID in JavaScript?

A) getElementByTag

B) getElementById

C) selectElementById

D) selectById

Answer: B) getElementById

Question: What method is used to select elements by their class name?

A) selectElementsByClass

B) getElementsByClassName

C) getElementByClass

D) selectClassElements

Answer: B) getElementsByClassName

Question: To select elements by their tag name, which method is used?

A) selectTagElements

B) getElementsByTag

C) getElementsByTagName

D) selectElementsByTag

Answer: C) getElementsByTagName

Question: How do you select an element using a CSS selector in JavaScript?

A) selectBySelector

B) getByCSS

C) selectElementByCSS

D) querySelector

Answer: D) querySelector

Question: To select all elements with a specific class using a CSS selector, which method is used?

A) selectAllByClass

B) getElementsByClass

C) querySelectorAll

D) selectElementsByCSS

Answer: C) querySelectorAll

Question: How do you select an element based on its attribute in JavaScript?

A) selectByAttribute

B) getElementByAttribute

C) querySelector

D) querySelectorAll

Answer: C) querySelector

Question: What method is used to select the parent element of a given element?

A) getParentElement

B) getElementParent

C) parentElement

D) selectParent

Answer: C) parentElement

Question: To select all sibling elements of a given element, what approach can be used?

A) getSiblingElements

B) siblings()

C) querySelectorAll

D) Array.from(parentElement.children).filter()

Answer: D) Array.from(parentElement.children).filter()

Question: How do you select elements based on a data attribute in JavaScript?

A) selectByAttribute

B) querySelectorAll(‘[data-attribute]’)

C) getElementsByAttribute

D) querySelector(‘[data-attribute]’)

Answer: B) querySelectorAll(‘[data-attribute]’)

Question: To select the third li element within a ul, what CSS pseudo-class can be used?

A) :nth-child(3)

B) :third-child

C) :select(3)

D) :child(3)

Answer: A) :nth-child(3)

Question: How can you change the text content of an element selected by ID?

A) element.textContent = “New Content”;

B) element.text = “New Content”;

C) element.innerText = “New Content”;

D) element.innerHTML = “New Content”;

Answer: A) element.textContent = “New Content”;

Question: What property is used to change the background color of an element in JavaScript?

A) element.style.color

B) element.style.background

C) element.style.backgroundColor

D) element.background

Answer: C) element.style.backgroundColor

Question: How do you log the text content of multiple elements selected by class name?

A) console.log(element.text);

B) console.log(element.textContent);

C) console.log(elements[i].innerText);

D) console.log(elements[i].text);

Answer: B) console.log(element.textContent);

Question: Which method is used to select all p elements inside a div with class “nested”?

A) querySelectorAll(‘.nested p’);

B) getElementsByClassName(‘nested p’);

C) querySelectorAll(‘div.nested p’);

D) getElementsByTagName(‘div.nested p’);

Answer: A) querySelectorAll(‘.nested p’);

Question: How do you select the input element with the attribute type=”text”?

A) querySelector(‘input[type=”text”]’);

B) getElementByAttribute(‘type=”text”‘);

C) querySelector(‘input[text=”text”]’);

D) getElementByTag(‘input[type=”text”]’);

Answer: A) querySelector(‘input[type=”text”]’);

Question: What is the purpose of the parentElement property in JavaScript?

A) To select the parent element of the current element.

B) To create a new parent element.

C) To modify the parent-child relationship of elements.

D) To check if an element has a parent.

Answer: A) To select the parent element of the current element.

Question: How can you select the second paragraph element with the class “paragraph”?

A) document.querySelector(‘p.paragraph[1]’);

B) document.querySelectorAll(‘p.paragraph’)[1];

C) document.getElementsByClassName(‘paragraph’)[1];

D) document.querySelector(‘p.paragraph:nth-child(2)’);

Answer: B) document.querySelectorAll(‘p.paragraph’)[1];

Question: What is the purpose of the querySelector method in JavaScript?

A) To select elements by their tag name.

B) To select elements by their class name.

C) To select elements using CSS selectors.

D) To select elements by their ID.

Answer: C) To select elements using CSS selectors.

Question: How do you select all elements with the data attribute data-role=”section”?

A) document.querySelector(‘[data-role=”section”]’);

B) document.querySelectorAll(‘[data-role=”section”]’);

C) document.getElementsByAttribute(‘data-role=”section”‘);

D) document.querySelectorAll(‘data-role=”section”‘);

Answer: B) document.querySelectorAll(‘[data-role=”section”]’);

Question: Which CSS pseudo-class is used to select even-numbered elements?

A) :odd

B) :even

C) :nth-child(even)

D) :nth-child(2n)

Answer: C) :nth-child(even)

Question: How can you select the last child element of a parent element in JavaScript?

A) parentElement.lastChild;

B) parentElement.querySelector(‘:last-child’);

C) parentElement.childNodes[parentElement.childNodes.length – 1];

D) parentElement.lastElementChild;

Answer: D) parentElement.lastElementChild;

Question: What method is used to select the first child element of a parent element in JavaScript?

A) parentElement.firstChild;

B) parentElement.querySelector(‘:first-child’);

C) parentElement.childNodes[0];

D) parentElement.firstElementChild;

Answer: D) parentElement.firstElementChild;

Question: How can you change the font size of an element with the ID “myText” to 16 pixels?

A) document.getElementById(‘myText’).style.fontSize = ’16px’;

B) document.querySelector(‘#myText’).fontSize = ’16px’;

C) document.getElementById(‘myText’).fontSize = ’16px’;

D) document.querySelector(‘#myText’).style.font.size = ’16px’;

Answer: A) document.getElementById(‘myText’).style.fontSize = ’16px’;

Question: What does the innerHTML property do in JavaScript?

A) Gets the text content of an element.

B) Sets the HTML content of an element.

C) Gets the HTML content of an element.

D) Sets the text content of an element.

Answer: C) Gets the HTML content of an element.

Question: How do you select the second div element within a parent element?

A) parentElement.querySelector(‘div:nth-child(2)’);

B) parentElement.querySelectorAll(‘div’)[1];

C) parentElement.querySelector(‘div:nth-of-type(2)’);

D) parentElement.querySelector(‘div[2]’);

Answer: C) parentElement.querySelector(‘div:nth-of-type(2)’);

Question: What is the purpose of the querySelectorAll method in JavaScript?

A) To select all elements with a specific ID.

B) To select the first element with a specific class.

C) To select all elements that match a given CSS selector.

D) To select the parent element of the current element.

Answer: C) To select all elements that match a given CSS selector.

Question: How can you log the index of each element in a NodeList selected by a CSS selector?

A) Use a for…in loop.

B) Use a forEach loop.

C) Use a while loop.

D) Use a for…of loop.

Answer: B) Use a forEach loop.

Question: Which method is used to select all direct children of a parent element?

A) parentElement.directChildren;

B) parentElement.children;

C) parentElement.querySelector(‘:children’);

D) parentElement.childNodes;

Answer: B) parentElement.children;

Question: How can you check if an element has a specific class in JavaScript?

A) element.hasClass(‘className’);

B) element.class === ‘className’;

C) element.classList.contains(‘className’);

D) element.className(‘className’);

Answer: C) element.classList.contains(‘className’);

Question: What is the purpose of the firstElementChild property in JavaScript?

A) To select the first child element of a parent.

B) To check if an element is the first child.

C) To select the first element with a specific class.

D) To select the first element of the document.

Answer: A) To select the first child element of a parent.

Question: How can you select the third paragraph element in a parent element with the class “content”?

A) document.querySelector(‘.content p:nth-child(3)’);

B) document.querySelector(‘.content p:nth-of-type(3)’);

C) document.querySelector(‘.content p’)[2];

D) document.querySelectorAll(‘.content p’)[2];

Answer: B) document.querySelector(‘.content p:nth-of-type(3)’);

Question: What does the innerText property do in JavaScript?

A) Gets the text content of an element.

B) Sets the HTML content of an element.

C) Gets the HTML content of an element.

D) Sets the text content of an element.

Answer: A) Gets the text content of an element.

Question: How do you select elements with the class “example” inside a parent element with the ID “container”?

A) document.querySelector(‘#container.example’);

B) document.querySelector(‘#container .example’);

C) document.querySelector(‘.container.example’);

D) document.querySelector(‘#container > .example’);

Answer: B) document.querySelector(‘#container .example’);

Question: What property is used to change the font color of an element in JavaScript?

A) element.style.color

B) element.style.fontColor

C) element.fontColor

D) element.color

Answer: A) element.style.color

Question: How can you select all even-numbered li elements within a ul using a CSS selector?

A) ul li:even

B) ul li:nth-child(even)

C) ul li:nth-of-type(even)

D) ul li:nth-even

Answer: C) ul li:nth-of-type(even)

Question: What is the purpose of the childNodes property in JavaScript?

A) To select all children of an element.

B) To check if an element has child nodes.

C) To get an array of child nodes.

D) To select the first child node.

Answer: A) To select all children of an element.

Question: How can you select all direct children with a specific class of a parent element?

A) parentElement.childrenByClass(‘.specificClass’);

B) parentElement.querySelector(‘.specificClass’);

C) parentElement.querySelectorAll(‘.specificClass’);

D) parentElement.getElementsByClassName(‘specificClass’);

Answer: C) parentElement.querySelectorAll(‘.specificClass’);