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

Testing a React component using the `ua-parser-js` plugin with Jest and React Testing Library

I've developed a simple component that displays an image depending on the operating system you are using (in this case, iOS and Android). import { UAParser } from "ua-parser-js"; export const DownloadApp = ({ appleStoreUrl, playStoreUrl }: ...

The tooltip in a scrollable container of Highcharts moves along with the content as it scrolls

I am currently facing an issue with my Highcharts instance that is displayed within a scrollable container. In addition, I have set the tooltip.outside option to true so that the tooltip always appears on top even if it exceeds the chart svg. The problem ...

React Native: A guide to triggering a modal or action sheet when a button tab is clicked using Wix React Native navigation

Is it possible to trigger a modal or actionsheet by clicking on a specific bottom tab in a tab-based application using wix react native v2 navigation? These are the current packages and versions I am working with: react-native : "0.59.8" react : "16.8. ...

What is the best way to utilize mysql for storing user state in order to restrict them from taking a particular action more than once per day?

< button type="button" id="daily-reward-button">Claim</button> 1) When a user clicks this button, it should be disabled which will result in the user being banned in the MYSQL database and unable to click the button again. 2) The button should auto ...

Tips for creating a sophisticated state transition diagram using Typescript

If you have a creative idea for a new title, feel free to make changes! I have two enums set up like this: enum State { A = "A", B = "B", C = "C" } enum Event { X = "X", Y = "Y", Z ...

Having difficulties accessing the properties of a dynamically created JSON object with ng-repeat functionality

Within an ng-repeat loop, I have implemented a radio button that assigns the entire person object to a scope variable as shown below: <li ng-repeat="person in people"> <label>{{person.name}} <input type="radio" ng-model="$parent.s ...

Updating and eliminating text within an array of objects using Vue JS

My Axios request pulls in an array of objects named 'uniquecolors'. Here is what it looks like: mycolors color: [GREEN, RED, BLUE, YELLOW, ORANGE,ORANGE,GREEN,] color: [GREEN, RED, BLUE, YELLOW, ORANGE,ORANGE,GREEN,] color ...

Issue with datepicker functionality not operational for newly added entries in the table

@Scripts.Render("~/bundles/script/vue") <script> var vueApp = new Vue({ el: '#holiday-vue', data: { holidays: @Html.Raw(Json.Encode(Model)), tableHeader: 'Local Holidays', holidayWarning: true, dateWarning: true }, methods: ...

Material UI Grid Items not stretching to fill the entire available width

I'm currently working with a nested Grid system in Material UI, but the Grid items are only occupying a fixed width and leaving some empty space. The issue arises when this fixed space is used up and instead of adjusting their internal free space, the ...

Is it possible to resize the background-image style?

When using the regular img tag in HTML, you can specify the width and height, and the browser will scale the image. If the dimensions are not too different from the original, the result is usually decent. For example, you can scale the avatar image to 32x ...

Using the clientWidth property in React

While I have a solid background in Javascript, I am relatively new to working with React. In my previous projects where I coded directly in javascript for the browser, I frequently used the following code snippet: width = document.getElementById('elem ...

Function for swapping out the alert message

I am searching for a way to create my own custom alert without interfering with the rendering or state of components that are currently using the default window.alert(). Currently working with React 15.x. function injectDialogComponent(message: string){ ...

Using an array.map inside a stateless component with React.createElement: the type provided is invalid

There is a component called BasicDetail in my code with the following structure: import React from "react"; import { Grid, Form } from "semantic-ui-react"; const BasicDetail = ({DetailData}) => { return( <div> <Grid.Ro ...

Having trouble generating a dynamic ref in Vue.js

I am currently working on rendering a list with a sublist nested within it. My goal is to establish a reference to the inner list using a naming convention such as list-{id}. However, I'm encountering difficulties in achieving this desired outcome. B ...

The continuous resizing of the window is triggering a loop in flexslider when the resize function is called

I am currently working on a website that utilizes the flexslider plugin. My goal is to detect when the browser window is resized, and then reinitialize the slider so that it can adjust its size and other parameters accordingly. Initially, I was able to a ...

React Alert Remove Alert: Each item in a list must be assigned a distinct "identifier" prop

How can I resolve the React warning about needing a unique "key" prop for each child in a list? I'm trying to eliminate the warning that says: "Each child in a list should have a unique key prop." The code snippet causing this warning is shown below ...

Executing a function to erase the stored value in local storage during an Angular unit test

Looking to verify whether the localStorage gets cleared when I execute my function. Component ngOnInit() { // Logging out when reaching login screen for login purposes this.authService.logout(); } authService logout() { // Removing logged i ...

hover causing the table cell to act erratically

My table consists of three cells with widths of 30%, 40%, and 30% respectively. The table itself occupies 25% of its container, which can range from 1024px to 400px. The first cell contains a button labeled GALLERY. Upon hovering over the cell, the text c ...

I'm trying to set it up so that an image pops up when I hover over text. I've tried incorporating a few different JavaScripts, but I still can

I'm struggling to display an image on my website. I have the necessary code parts, but it's not working as expected. function showImage() { $('.img').addClass('display'); } function hideImage() { $('.img'). ...

Troubleshooting MongoDB aggregate lookup failure when using multiple parameters

In my data retrieval process from the comments table, everything is functioning properly. However, I am aiming to optimize performance by performing a join equivalent on the users collection to fetch additional user details associated with each comment. B ...