In: Computer Science
Rewrite the query methods used in the JS statements in lines 17, 18, 19, and 20 by using querySelector() or querySelectorAll() methods. Note that your code has to return the same outputs on the console (in a browser's developer tab, Ctrl + Shift + J) before you make the changes.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Access HTML elements </title>
</head>
<body>
<section id="main">
<h1>The 2011-2012 Speaker
Lineup </h1>
<p class="blue">October 19,
2011: Jeffrey Toobin </p>
<p class="blue">November 16,
2011: Andrew Ross Sorkin </p>
</section>
<footer>
<p class="right">Copyright
2012 </p>
</footer>
<script>
var sec =
document.getElementById('main');//return the <section>
element which has id="main"
var list1 =
document.getElementsByTagName('p');//return the HTMLCollection
object containing 3 <p> elements that belongs to
class="blue"
var list2 =
sec.getElementsByTagName('p');//return the HTMLCollection object
containing 2 <p> elements
var list3 =
sec.getElementsByClassName('blue'); ////return the HTMLCollection
object containing 2 <p> elements in the <section>
element
console.log(sec);
console.log(list1);
console.log(list2);
console.log(list3);
</script>
</body>
The Document method querySelector() returns the first element within the document that matches the specified selector, or group of selectors. If no matches are found, null is returned. The selector can be of any type. It can be a class (.myclass), id (#myid) etc.
Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Access HTML elements </title>
</head>
<body>
<section id="main">
<h1>The 2011-2012 Speaker
Lineup </h1>
<p class="blue">October 19,
2011: Jeffrey Toobin </p>
<p class="blue">November 16,
2011: Andrew Ross Sorkin </p>
</section>
<footer>
<p class="right">Copyright
2012 </p>
</footer>
<script>
var sec = document.querySelector("#main"); // code added for returning the <section> element which has id="main"
var list1 = document.querySelectorAll("p"); //code added to return the NodeList object containing 3 <p> elements
var list_blue = document.querySelectorAll(".blue") //code added to return the NodeList object containing 2 <p> elements with class blue
var list2 = sec.querySelectorAll("p"); //return the NodeList object containing 2 <p> elements
var list3 = sec.querySelectorAll(".blue"); //return the NodeList object containing 2 <p> elements in the <section> element
console.log(sec);
console.log(list1);
console.log(list2);
console.log(list3);
// console.log(list_blue); // for giving the output of 2 <p> elements which has class blue
</script>
</body>
</html>
P.S: var list1 = document.getElementsByTagName('p');//return the HTMLCollection object containing 3 <p> elements that belongs to class="blue" returns all the <p> elements and it doesn't select the class with the class="blue".
Output :