Choose a specific item in jQuery that has a pair of attributes

https://jsfiddle.net/The95Chaps/2L4t9saq/92/ contains the following code:

var createGrid = function(rows, columns, width, height) {
    for (var r = 1; r < rows + 1; r++) {
        var rowHtml = "<span class='inline'>";
        for (var c = 1; c < columns + 1; c++) {
            rowHtml += "<div class='pixels' x='" + c + "' y='" + r + "'></div>";
        }
        rowHtml += "</span>";
        $("#main").append(rowHtml);
    }
    $(".pixels").css("background-color", "gray");
    $(".pixels").css("width", width);
    $(".pixels").css("height", height);
};

var modifyGrid = function(code) {
    for (var i = 1; i < gridx + 1; i++) {
        for (var j = 1; j < gridy + 1; j++) {
            $("[x=" + j + "][y=" + i + "]").css("background-color", "blue");
        }
    }
};

var gridx = 64;
var gridy = 64;

createGrid(gridx, gridy, 1, 1);

.

<div canvas="canvas" id="main"></div>

.

.inline { display: block; }
.pixels { display: inline-block; }
#main {
  font-size:0;
}

The initial setup creates a 64 by 64 grid where each pixel is 1 unit in size, totaling 4096 pixels.

In the modifyGrid() function, the intention is to take a JavaScript array and convert it into an image. The challenge lies in the jQuery selectors.

Currently, the selection relies on

$("element[attribute=value]").somefunction();
. The question at hand is how to select elements with two attributes, specifically when both 'x' and 'y' should match certain values simultaneously.

Within the for loop, the goal is to identify pixels where the 'x' attribute matches 'i' and the 'y' attribute matches 'j', and then change their background color to blue using

$(selector[x=someValue][y=someValue]).css("background-color","blue");

Answer №1

You are unable to utilize two attribute selectors simultaneously.

However, you can instead use just one selector to obtain a collection of elements that match. Then within this collection, locate the specific element that also matches the second attribute.

Employing an .each() loop will be beneficial in this scenario.

var createGrid=function(s,i,a,e){for(var r=1;r<i+1;r++){for(var c="<span class='inline'>",n=1;n<s+1;n++){c=c+"<div class='pixels' x='"+n+"' y='"+r+"'></div>"}c+="</span>",$("#main").append(c)}$(".pixels").css("background-color","gray"),$(".pixels").css("width",a),$(".pixels").css("height",e)};
var modGrid = function(code){
    for(var n=1;n<gridx+1;n++){
        for(var i = 1; i<gridy+1; i++){
        $("[x="+i+"]")
    }
    }
}
var gridx = 64
var gridy = 64
createGrid(gridx,gridy,1,1)

// For targeting the pixel at (10,10)
$("[y='10']").each(function(){
  if($(this).is("[x='10']")){
    $(this).css("background-color","blue");
  }
});
.inline { display: block }
.pixels { display: inline-block }
#main {
  font-size:0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div canvas="canvas" id="main"></div>

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

Get the data in string format and save it as a CSV file

I've coded a script that transforms a JSON object into comma-separated values using the ConvertToCSV function. Now I'm wondering how to save the variable csvData as a downloadable CSV file? The code is already wrapped inside a function triggered ...

After running the JavaScript function, the temporary display of textbox is initiated

I am trying to implement a feature where a textbox is shown or hidden when a user clicks on a filter icon in the header of a gridview. Initially, the textbox is hidden but when the icon is clicked, it briefly appears before disappearing again as if the pag ...

JQuery for sending posts rapidly with Ajax interactions

My ajax request to Express is not getting a response. The post request status stays pending for a long time in the Chrome inspector network tab before failing. Below is my express code snippet: app.configure(function(){ app.set('port', process ...

Real-time Property Availability Widget

I need assistance with creating a website for a homeowner who wants to rent out their property. The client requires a feature that allows them to log in and easily mark individual days as available or unavailable for rental by choosing specific colors for ...

Why does changing the order of layers in Kinetic.JS affect the color of my shapes?

Currently experimenting with Kinetic.JS, I managed to create a UFO-like shape using two parts - a red hull and a grey disc. Check out the demo on JSBin My question is: why does the color of the disc change from grey to red when I rearrange the shape orde ...

Retrieving information from a JSON file using AngularJS

Hello, I am a beginner in Angularjs and I am facing an issue while trying to retrieve data from a JSON file. The output I am getting is quite strange. Below are snippets from my controller.js and services.js files: angular .module('app') .contro ...

jQuery UI has encountered an issue: it seems that #accordion is not a recognized function

While attempting to integrate jQuery UI Accordion into a webpage, I encountered an error message in Firebug upon loading the page: #accordion is not a function The jQuery code I am using is as follows: <script type="text/javascript"> $(document).r ...

Utilizing the Fetch API to append JSON data to the document in Javascript

I am working on sending JSON data back to my express app using fetch and a POST method. Here is the code snippet I have: fetch('https://development.c9users.io/canadmin',{ method:'POST', body:JSON.string ...

The background color property of the CSS class "ui-layout-north

Currently working with primefaces 4.3 and incorporating it into my main UI. My goal is to modify the background color of the north unit to red, as currently only the top 80% of the unit is affected. .ui-layout-north .ui-layout-unit-content { backgro ...

Stopping the interval in Javascript on button press

Struggling to make clearInterval work properly when connected to a button click action. Also, the function seems to be activating on its own... Take a look at my code below var funky = setInterval(function() { alert('hello world'); }, 2000); ...

Angular - Mongoose: Struggling to handle date values

I have been searching for a solution for quite some time now, but unfortunately, nothing has worked for me. My Angular JS application is running with Mongoose and Express. I am trying to store date as an object from a simple form. However, after submitti ...

The W3C Validator has found a discrepancy in the index.html file, specifically at the app-root location

While attempting to validate my HTML page, I encountered the following error: Error: Element app-root not allowed as child of element body in this context. (Suppressing further errors from this subtree.) From line 4347, column 7; to line 4347, column 16 ...

Retrieve data from an SQL database and populate an HTML dropdown menu in a web page using PHP

I am a beginner in the world of JavaScript and facing some challenges. I am working with PHP 7 and attempting to retrieve data from an SQL database, specifically a table. My goal is to extract a single column from this table and display it in a dropdown me ...

A tailor-made Angular filter designed to exclusively show items falling within a specific date range

Hi there! I am currently delving into AngularJS and working on an application that pulls articles via JSON. My goal is to display items within a specific date range when a button is clicked. While I have the logic figured out, I am unsure of how to approac ...

Bug in SQL causing issues between PHP client and server

I can't seem to pinpoint the issue with this code. Basically, I am sending a username and password to the server, which then sends back a response. The server successfully writes to the database, but on the client side, sometimes it fails to reach in ...

Is there a way to refresh a specific section of a view using an Ajax response in Yii version 1.1.14?

In this scenario, upon loading the page initially, it populates data from a Yii widget by utilizing: $this->widget(blahblabhablha) Within this widget, there exists a clickable dropdown menu. Upon selecting an option, it triggers an ajax call. Subseque ...

When the component is initialized, the computed property is not being evaluated

My maps component initializes a Google map, adds markers based on props passed from the parent, and sets the correct bounds of the map. However, the markers are added through a computed property to make it reactive. Everything seems to be working fine, exc ...

I am looking to download a file from a server and showcase it in a browser using React.js. The file will be received as a response from the

**I am looking to retrieve a file from the server by sending the file name through the body and then receiving the requested file from the server.** I have successfully received the file in response from the server, which I tested using Postman. What I a ...

Postman is displaying [object object] as the return value, but the actual value is not

Currently, I am working on automating tasks using Postman One interesting aspect is the presence of a vehicles array in the body { "Vehicles":[ { "car":"{{car}}", "bike":"{{bike}}&quo ...

Dynamically validate AngularJS forms with JSON Schema

I am currently trying to dynamically validate JSON in AngularJS. Unfortunately, I have encountered an issue with loading fields from the schema onto the page. My understanding of AngularJS is limited as I am still new to it. Although I have managed to cr ...