chaps
chaps

Reputation: 105

Select an element in jquery with two attribiutes

https://jsfiddle.net/The95Chaps/2L4t9saq/92/ is my code

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)

.

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

.

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

just ignore the top line, all it does is creates the array

so currently it creates a 64 by 64 grid, each pixel is 1 pixel in size, and the total amount of pixels are 4096 pixels

in my modGrid() function it is going to be able to take in a JS array and then convert it into an image, but i am having some trouble with jquery selectors.

currently the only way i know how to select an element with specific attribiutes is using $("thing[attribute=blah]").somefunction(); and i was just wondering

since i am selecting by 2 attributes (x and y) how would i do this?:

inside the for(var i){}; loop it should be able to select a pixel with attribiute x to equal i and attribiute y to equal n, and change the selected pixels color to blue, using $(selector[x=yada and y=yada).css("background-color","blue");

Upvotes: 0

Views: 55

Answers (1)

Louys Patrice Bessette
Louys Patrice Bessette

Reputation: 33933

You cannot use two attribute selectors at once.

But what you can do is to use one... So you get a collection of matching elements. Inside this collection, just find the one that is also matching the second attribute.

An .each() loop will do.

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)

// To target 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>

Upvotes: 1

Related Questions