Looking for an alternative to document.querySelectorAll?

My issue involves using querySelectorAll('a') to select all buttons, but I only want to target two specific buttons labeled 'Know More'. How can I achieve this?

Below is the code snippet in question:

const buttons = document.querySelectorAll('a');
buttons.forEach(btn => {
  btn.addEventListener('click', function(e) {

    var totalOffsetX = 0; // X and Y COORDINATES WITH SCROLL START
    var totalOffsetY = 0;
    var X = 0;
    var Y = 0;
    var currentElement = this;

    do {
      totalOffsetX += currentElement.offsetLeft - currentElement.scrollLeft;
      totalOffsetY += currentElement.offsetTop - currentElement.scrollTop;
    }
    while (currentElement = currentElement.offsetParent)

    X = e.pageX - totalOffsetX;
    Y = e.pageY - totalOffsetY; // X and Y COORDINATES WITH SCROLL END

    let ripples = document.createElement('buttonspan');
    ripples.style.left = X + 'px';
    ripples.style.top = Y + 'px';
    this.appendChild(ripples);

    setTimeout(() => {
      ripples.remove()
    }, 1000);
  })
})
<div class="buttons">
  <a href="javascript:void(0)">Know More</a>
  <a href="javascript:void(0)" class="button">Know More</a>
</div>

Answer №1

To easily filter a collection retrieved using querySelectorAll(), you can convert it to an array and apply the .filter() method.

const buttons = [...document.querySelectorAll('a')].filter((x) => x.innerText==="Know More");
       
       console.log(buttons);
       buttons.forEach((a) => { a.addEventListener('click',()=>{
       console.log("yo"); });
       });
<div class="buttons">
      <a href="javascript:void(0)">Know More</a>
      <a href="javascript:void(0)" class="button">Know More</a>
      <a href="#a">Know Less</a>
    </div>

Tip: To simplify filtering, consider assigning relevant class names to elements with specific content like 'Know More' before selecting them with querySelectorAll().

let buttons = document.querySelectorAll('a.knowmore');

The return type of querySelectorAll() is a NodeList rather than an array, hence the need to use the spread operator ... to convert it before applying the .filter() method.

The usage of .forEach() in your code works because it's implemented on the NodeList, but keep in mind that older browsers like Internet Explorer may lack support for this method.

Some older browsers have not implemented NodeList.forEach().

Answer №2

To specify which specific buttons you want to select, you can utilize either the id element or the class element as shown below:

<a class="foo">...</a>
<a>...</a> //will not be selected
<a class="foo">...</a>

Once this is done, proceed to use the appropriate CSS selector for the selection process.

document.querySelectorAll("a.foo")...

Answer №3

Unfortunately, there is no CSS selector that can specifically target the content within an element. While jQuery offers a :contains() extension for this purpose, it is not supported in standard querySelectorAll().

In order to achieve this functionality, you will need to manually check for the desired content within your loop:

buttons.forEach(btn => {
  if (btn.textContent.trim() == 'Know More') {
    // Add your code here
  }
});

Answer №4

To target specific elements, I suggest assigning a unique class name to them and then utilizing the document.getElementsByClassName method in your JavaScript code.

const targetedElements = document.getElementsByClassName('special-elements');

console.log(targetedElements);
<div class="buttons">
  <a href="javascript:void(0)" class="special-elements">Special Element</a>
  <a href="javascript:void(0)" class="button special-elements">Special Element</a>
</div>

Answer №5

To selectively retrieve specific elements, you can leverage the filter method.

const links = [...document.querySelectorAll('a')];
const exploreButtons = links.filter(link => link.textContent === 'Explore')

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Add United States as an additional attribute to the countries retrieved from the API

I am working with an API that provides data in a specific format: [ { "id": 12, "acf": { "address": { "city": "Bandar Penawar", "state": "Johor", "country ...

The battle of efficiency: Generating content from JSON files compared to pulling from a

Greetings, fellow forum members! This is my inaugural post here. Despite the title possibly hinting at duplication, I have come across similar posts such as: one, two, three, four, and so on. However, my query bears a slight variation. I am currently in th ...

There is no index signature that accepts a parameter of type 'string' in the type '{ [key: string]: AbstractControl; }'

I'm currently tackling a challenge in my Angular project where I am creating a custom validator for a reactive form. However, I've encountered an error within the custom validators function that I am constructing. Below you will find the relevan ...

React 18 introduces a new feature, ReactDOMClient.createRoot(), which allows for hot module replacement with Webpack. This allows developers to update components in real time without

After upgrading React to version 18, I encountered a console error with my Webpack dev server when the hot module replacement triggers and injects new JavaScript code: Warning: You are calling ReactDOMClient.createRoot() on a container that has already be ...

Is there a way to prevent the back button from functioning in my web browser?

How can I prevent the back button from being used on my webpage? Can you provide a list of possible methods to achieve this? if($data->num_rows > 0){ while($row = $data->fetch_assoc()){ header('Location:../cashier.php&apo ...

Utilizing Google Tag Manager for Efficiently Managing Multiple Schema Product Reviews with JSON-LD and Variables

Currently, I am facing a challenge while using Google Tag Manager to incorporate Schema JSON-LD Product reviews on certain pages. Despite my efforts, I am unable to locate any relevant resources to resolve this issue. The main problem lies in informing GT ...

How can we prevent an unstyled list from causing text to drop to the next row?

As I am not an expert developer, I am in the process of creating a basic menu card using bootstrap. To keep it simple, I decided to use an unstyled list and added a span with float: right to ensure that the price is always aligned to the right. However, I ...

Solving issues with flexboxes in Safari 5.1.7 on Windows

I am currently utilizing flex boxes for managing the layouts of my website. However, it seems that the Safari version for Windows (5.1.7) is outdated and causing all flex boxes to be dysfunctional. On MacOS systems, the same version 12.x works correctly. ...

Comparing the benefits of a 3-column flow layout to a traditional

I've been wondering about the popularity of 3 column flow layouts compared to using a table with 3 columns and one row. Can someone explain the advantages and disadvantages of using a flow layout versus a table layout for this scenario? Thank you ...

Having trouble passing a token for authentication in Socket.IO v1.0.x?

I am currently following a tutorial on creating a token-based authentication system, which can be found here. I have implemented the following code: Code in app.html: var socket = io('', { query: "token=i271az2Z0PMjhd6w0rX019g0iS7c2q4R" }); ...

Unable to open Google Maps link within React application

I've set up a conditional link based on location, using the following code: <a href={`https://maps.google.com/maps?q=${delivery_branch.latitude},${delivery_branch.longitude}`} target={"_blank"} >{`${delivery_branch.street}, ${d ...

Tips for extracting only a portion of the JavaScript timestamp

I have a JavaScript timestamp that reads Tue Sep 30 2014 12:02:50 GMT-0400 (EDT). When I use the .getTime() method, I get 1412092970.768 Typically, this timestamp represents a specific time of today. My question is whether it's possible to extract o ...

When a div is covered by an if statement

One of the challenges I am facing is managing a view with multiple projects, some of which are active while others are not. In my function, if a project's deadline has passed, it displays '0' days left on the view, indicating that these are ...

Modifying the appearance of the login field shown in the image

How can I align the login and password fields in the same order on my webpage? When I attempt to adjust their positions using CSS margin commands, both fields end up moving. Any suggestions? ...

Node.js: Issues with using async await inside a map function

Currently, I am in the process of developing a clone of Tinder. My focus right now is on working on the match/post request within my backend code. This request involves calling a separate function named match, which is triggered after the current user ha ...

Could an element's loading be postponed on the initial page a user lands on?

One of my clients has requested a live chat system to be added to their website. I am fully capable of implementing it, and it is included through a script tag. Additionally, they have asked for a slight delay before the chat system loads in. My initial t ...

Concealed text hidden beneath a Sticky Navigation Bar (HTML/CSS)

I'm in the process of creating a simple website that includes a sticky Navigation Bar. However, I'm encountering an issue where text added to the website is being hidden behind the Navbar. Is there a way for me to adjust the positioning of the te ...

How to efficiently eliminate duplicates from an array list using React framework

Keeping the array name constant while duplicating and repeating this process only clutters the list. Appreciate your help. setListItems(contents.data); console.log(contents.data); ...

Display a hyperlink in an iframe on the main page from a different domain using JavaScript

I'm currently using Angular with Wirecard as my payment provider. When I need to add a payment, I open an iframe that directs the user to the Wirecard site to accept the payment. Once the user clicks accept, I provide a link back to my site from Wirec ...

Placing pins on Google Maps

I'm attempting to display two separate markers on two individual maps positioned next to each other on my website. <script type="text/javascript"> var map, map2; function initialize(condition) { // setting up the maps var myOptions = { zoo ...