Ask Your Question
1

How can I use the class selector instead of the ID selector to choose an element in javascript?

asked 2022-02-12 11:00:00 +0000

qstack gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2022-03-05 18:00:00 +0000

lalupa gravatar image

To use the class selector instead of the ID selector to choose an element in JavaScript, you can use the document.querySelector method or the document.querySelectorAll method. Here are the steps:

  1. Get the element(s) using the document.querySelector or document.querySelectorAll method
  2. Use the class name selector as the argument for the querySelector or querySelectorAll method
  3. Use the selected element(s) as needed

Here's an example:

HTML:

<div class="my-class">Hello world!</div>
<div class="my-class">Goodbye world!</div>

JavaScript:

// Get the first element with class name "my-class"
var firstElement = document.querySelector(".my-class");
console.log(firstElement.textContent); // Output: "Hello world!"

// Get all elements with class name "my-class"
var allElements = document.querySelectorAll(".my-class");
console.log(allElements.length); // Output: 2
console.log(allElements[1].textContent); // Output: "Goodbye world!"
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-02-12 11:00:00 +0000

Seen: 7 times

Last updated: Mar 05 '22