Is there a way to utilize Javascript to retrieve elements without specifying an id?

I am faced with a challenge of accessing an element without an id but with a shared classname using Javascript. How can I accomplish this task successfully?

My attempt to use the document.getElementsbyClassName property was unsuccessful due to the shared classname among other elements.

   <a class="sharedClass anotherClass" href="www.mybooks.com" data-m="{"CN":"uniquename"}"> Proceed </a>

I aim to click on the Proceed element in the code snippet above, where uniquename uniquely identifies this specific element. I believe there might be a way to leverage this unique identifier for my task, although I'm unsure of the exact approach.

Answer №1

As @Buffalo hinted in their comment, one way to achieve this is by fetching a list of all elements with the same class name and then iterating over the results to locate the desired element based on its data-m attribute:

var elements = document.getElementsByClassName("sharedClass");
var myElement;
for (var i = 0; i < elements.length; i++) {
  if (elements[i].getAttribute("data-m") == '{"CN":"uniquename"}') {
    myElement = elements[i];
  }
}

console.log(myElement);
<a class="sharedClass anotherClass" href="www.mybooks.com" data-m='{"CN":"uniquename"}'> Proceed </a>
<a class="sharedClass anotherClass" href="www.mybooks.com" data-m='{"CN":"uniquename2"}'> Proceed </a>

Alternatively, you can use a more concise approach by utilizing querySelector:

var myElement = document.querySelector("[data-m='{\"CN\":\"uniquename\"}");
console.log(myElement);
<a class="sharedClass anotherClass" href="www.mybooks.com" data-m='{"CN":"uniquename"}'> Proceed </a>
<a class="sharedClass anotherClass" href="www.mybooks.com" data-m='{"CN":"uniquename2"}'> Proceed </a>

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

Refresh the DIV element that houses dynamically generated <ul> HTML content after submitting new inputs

UPDATE: After delving into the code of nested include files in the child PHP file, I've identified conflicts with the parent PHP include files. This means that the child PHP file/div relies on the parent being refreshed, preventing me from refreshing ...

Dealing with form errors - Using Node.js and Express Framework

Is there a way to handle errors that occur when dealing with null form inputs or unavailable cities from the weather api service? Sometimes, when an empty query or a misspelled city is inputted, the server returns errors and halts operation. app.get("/", ...

Validation needed for data list option

Here are all the details <form action="order.php" method="post" name="myForm" onsubmit="return(validate());"> <input type="text" list="From" name="From" autocomplete="off" placeholder="From Place"> <datalist id="From"> <option valu ...

The most effective way to code overlapping html buttons

Can you help me figure out how to make clickable areas on my HTML5 web page without them overlapping? Here's what I'm trying to do: I want the red, blue, and green areas to be clickable links, but not overlap. For example, when clicking on the f ...

Gather data from various textboxes and combine them into a unified string with the help of JavaScript

I am currently facing a challenge where I need to extract the values from multiple textboxes and combine them into a single string. This string will then be sent to my PHP processing page for insertion into a database table. The textboxes mentioned above ...

The execution of my code differs between running it locally and in online code editors like CodePen or Plunker

Using jQuery Terminal, I have the following code: function display() { for (var i = 0; i < 100; ++i) { this.echo('line ' + i, { flush: false }); } this.flush(); setTimeout(function() { //thi ...

Switch to display only when selected

When I click on the details link, it will show all information. However, what I actually want is for it to toggle only the specific detail that I clicked on. Check out this example fiddle Here is the JavaScript code: $('.listt ul').hide(); $( ...

When utilizing useMachine in TypeScript, an error is thrown regarding incompatible types

While attempting to build my first example for a xstate finite machine by following the example on github.com/carloslfu/use-machine, I encountered a TypeScript error that halted my progress: Argument of type '{ actions: { sideEffect: () => void; } ...

When a task hasn't been completed within a 3-second timeframe, execute a specific block of code

I need to incorporate a promise in my code to execute angular.bootstrap() in block 2 if 3 seconds have passed and angular.bootstrap() in block 1 has not been completed. I have two separate blocks of code: // block 1: Office.initialize = function (reason) ...

Issue with child rows not functioning properly in DataTables when utilizing Datetime-moment

I've successfully integrated this data into live.datatables.net and almost have it running smoothly. However, I am encountering an issue with displaying the last detail as a child element. The final part of the row should be shown with the label "Mes ...

Encountering an issue with Firebase Cloud Messaging

I am struggling to implement a push notification trigger whenever a document field is updated. As a newcomer to node.js, I am facing challenges in debugging what seems like a simple function. Below is the code snippet: // Cloud Functions for Firebase SDK ...

Troubleshooting AngularJS $q Promise Not Being Returned

I have encountered an issue while trying to call a service method in AngularJS. The service method is being called successfully, but it is not returning any value to the controller function that invoked it. If anyone can offer assistance, I would greatly ...

Crosswalk code unable to detect electronic devices

The implementation of a rails application involves the following code snippet: <div id="sourceSelectPanel" style="display:none"> <label for="sourceSelect"& gt;Change video source:& lt;/label> <select id=" ...

Ordering and displaying data with AngularJS

Trying to maintain a constant gap of 5 between pagination elements, regardless of the total length. For instance, with $scope.itemsPerPage = 5 and total object length of 20, we should have 4 pages in pagination. However, if $scope.itemsPerPage = 2 and tota ...

Sorting price and date with Vue in Laravel - A beginner's guide

Attempting to sort by price and by date. See the code below. I decided not to use the controller for this sorting. Is it feasible to implement it here? It's somewhat functional, but there are some issues. When selecting price, it doesn't seem to ...

Using MySQL data in an EJS file to create a personalized Profile Page

In the midst of a personal project aimed at honing my web development skills and gaining a deeper understanding of the intricacies of the field, I have hit a roadblock. The focus of this project is to create a profile page, and while I have successfully co ...

What is the purpose of deserializing the user for every request using PassportJS?

While I have scoured the official documentation and various online resources, I am still unable to find a solution to what seems like an obvious question. When working with Passport.js, it is necessary to define two methods - one for serializing and one f ...

Is using parameterized routes in Node.js a recommended practice or a mistake?

Here is the code snippet I'm working on: router.delete('/delete-:object', function(req, res) { var query; var id = req.body.id; switch (req.params.object) { case 'news' : query = queries['news_del ...

Error: The function authClient.request is not recognized in Node.js with googleapis

I am currently utilizing googleapis and google auth for managing events on Google Calendar. While I was able to successfully fetch the calendar event list, encountering an error when attempting to insert a new event. The error message being thrown is: Type ...

Is it possible to have the background scroll downward while keeping some content centered in place at all times?

Attempting to achieve the following effect in JavaScript, HTML, and Sass: When scrolling down the page, the layers (ground, sky, space, etc.) move downward The content (a rocket flying in the sky) stays centered on the screen and will move horizontally l ...