What is the most efficient method for retrieving an element using a data attribute with an object (JSON) value?

Imagine having the following HTML element:

<div class='element' data-info='{"id":789, "value":"example"}'></div>

By running this JavaScript code, you can access the object stored in the data attribute.

console.log($('.element').data('info'));

You can also retrieve specific data values like any other object.

console.log($('.element').data('info').value); //returns 'example'

Is there a way to select this element based on the data saved in its attribute? The initial attempt does not yield the desired results.

$('.element[data-info.id=789]');

It is possible to iterate through all instances of the element and check their data properties.

var idToFind = 789;
$('.element').each(function () {
  if ($(this).data('info').id == idToFind) {
    // perform an action
  }
});

However, could this be inefficient? Are there alternative methods to achieve the same outcome without using a loop? Is iterating over elements slower than utilizing a selector?

Answer №1

If you're looking to improve efficiency, consider utilizing the contains selector:

var key_var = 456;
$(".selector[data-object*='foreign_key:" + key_var + "']");

This could potentially offer faster performance compared to a loop as jQuery likely uses native JavaScript function string.indexOf() for parsing attribute values. However, be cautious with proper formatting as spacing errors can disrupt the matching process.

A drawback is that this method may also match similar patterns like:

<div class='selector' data-object="{primary_key:123, foreign_key:4562}"></div>

To refine the search, consider specifying the closing bracket in the selection string:

$(".selector[data-object*='foreign_key:" + key_var + "}']");

Though again, accuracy in formatting is crucial. An alternate approach could involve a combination of methods:

var results = $(".selector[data-object*='" + foreign_key + "']").filter(function () {
    return ($(this).data('object').foreign_key == foreign_key)
});

This will first filter elements containing the number sequence and then verify the exact matching value with a filter function.

Answer №2

Using an attribute selector that checks for containment.

$('selector[data-object*="foreign_key:456"]')

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

Is it possible to extract the selected indexes of all select menus in my HTML and assign them to various arrays of my choosing? I find myself writing a lot of code just for one select menu

In order to determine which TV character the user most closely resembles based on their answers to a series of questions, I have created a function. However, my current code is inefficient when it comes to handling multiple select menus! I am considering i ...

Issue: Module 'blog' not found in the specified path in my Node.js application

this snippet showcases my code in routes/blog.js var express = require('express'); var router = express.Router(); const Blogs = require("../models/blog"); and here is the code from models/blog.js const mongoose = require('mongoose ...

Retrieve a JSON object from a JSON array using a specific key

I am facing a situation where I have a json array containing multiple json objects. Let's take the example of a course object with the following structure: {"name": "Math", "unit": "3"} The json array looks something like this: [{"name": "Math", "u ...

Adjust the size of an input field in jquery or javascript based on user input

Ensure that an input text box can only contain a maximum of 13 numbers, but if the user enters a 14th number as a decimal point, then allow up to 16 numbers. HTML: <input type="text" maxlength="15" onkeyup="checkCurrency(this)"/> Script: func ...

The next-routes server.js encounters an issue: TypeError - the getRequestHandler function is not defined within the routes

I encountered an issue in my server.js file. Here is the code snippet causing the problem: const { createServer } = require('http'); const next = require('next'); const routes = require('./routes'); const app = next ({ dev: ...

iOS 10's autofocus feature experiencing difficulties in focusing on input

While using an application on my desktop or Android device, I have noticed that the input focus works perfectly fine. However, when I try to run the same application on iOS 10 Safari, the input focus does not seem to be working. It is worth noting that I ...

Angular JS page in its purest form

I have successfully developed a single-page application using AngularJs. However, when I visit the main page of my application hosted on the Heroku server, for a brief moment, all the images and text appear in a raw state at the top left corner of the bro ...

Establishing numerous websocket connections within a singular application

I am looking to conduct load testing on our websocket service. Is there a method to establish multiple websocket connections from one workstation? My attempt with npm ws and websocket modules in conjunction with NodeJS was successful for a single connecti ...

Using Node.js and Less to dynamically select a stylesheet source depending on the subdomain

Currently, my tech stack consists of nodejs, express, jade, and less. I have set up routing to different subdomains (for example: college1.domain.com, college2.domain.com). Each college has its own unique stylesheet. I am looking for a way to selectively ...

Tips for changing the JSON result of a method in a WCF service

I'm currently exploring how to customize the name of the JSON object returned from a WCF service to a web client via an AJAX call, rather than using the default wrapper. Despite my efforts, I haven't been able to find any relevant articles on thi ...

Retrieving Information from a JSON Object using Angular 2

I'm dealing with a JSON object response. The object looks like this: {auth_token: "60a483bc0b1bc4dc0231ff0b90a67be1dad6ef45"} auth_token:"60a483bc0b1bc4dc0231ff0b90a67be1dad6ef45" proto : Object My goal is to extract the value "60a483bc0b1bc4dc0231f ...

Using the Strikethrough Feature in React

Is it possible to apply a strikethrough effect to a checkbox's label text when toggled on and off? In my system development process, I've utilized various methods. What modifications should be made in the fComplete method for this feature to wor ...

Convert a Twitter Direct Message Link by changing the `<button>` tag to an `<a>` tag

When you log into Twitter and have Direct Message enabled, a "Send Message" button will appear. Can someone please provide the URL for sending a DM to a specific user? I tried looking at the code but I could use some assistance. Any thoughts? Thank you in ...

Alerting old session data following an AJAX request

After making an AJAX call that updates a $_SESSION variable, my <script> is supposed to echo out the new variable. However, it keeps alerting the old data even though the data is reaching the .php page and being stored in the session. I've attem ...

Getting the Tweets of a Twitter-validated user using node.js

I'm struggling with extracting Tweets from a verified user and could use some assistance. I know it's a broad question, but here's the situation: https://github.com/ttezel/twit provides a way to access tweets from any Twitter account. Howev ...

URL Image Cropping

Hello, I have been utilizing the iTunes API and have successfully saved the search data into my database. Currently, I am saving the image URLs from iTunes to my database and am seeking advice on the most efficient method to crop these images using PHP. ...

Executing a JavaScript code in a Python webdriver: A step-by-step guide

Using Selenium 2 Python webdriver: I encountered an issue where I needed to click on a hidden element due to a hover effect. In search of solutions to unhide and select the element, I came across the following examples: Example in Java: JavascriptExecut ...

The total height of an HTML element, which takes into account the margin of the element itself

Is there a way to accurately calculate the height of an element including margins, even when dealing with child elements that have larger margins than their parents? HTMLElement.offsetHeight provides the height excluding margin, while this function from ...

Easily fetching data with AJAX through jQuery

Completely new to using jQuery and AJAX, I attempted the code below for a simple http get request: <html> <head> </head> <body> <script src = "jquery-2.1.4.js"></script> <script src = "app.js"></script& ...

Discover the parent DOM element of a specified element using jQuery

When using jQuery, I am currently exploring methods to navigate through the DOM until it locates a specific selector. For instance: Consider this structure: <span data-type="contact" data-filter="4" id="buyer-lookup" class="uneditable-input contact-lo ...