Dan Rubio Dan Rubio - 1 month ago 10
CSS Question

Is there a way I can find a div element by both its css 'left' and 'top' attributes?

I have a list of div that look like this below:

<div class="blockattribute" id="1" style="background-color: rgb(217, 217, 217); left: 0px; top: 0px;"></div>


I have a bunch of these on a grid and as part of my floodfill algorithm, I want to select adjacent grids by
left
and
top
as my x and y coordinates. So far I can't seem to figure out how to get this to work. Does anyone have a recommendation as to how to accomplish this?

From a stackoverflow question I have tried the following selector:

$("div['style=left: 0px; top:0px;']");


I think this is close but I get this error:

jquery.min.js:2 Uncaught Error: Syntax error, unrecognized expression: div['style=left: 0px; top:0px;']

Answer

First off, your code $("div['style=left: 0px; top:0px;']"); is syntactically invalid. It needs quote around the attribute value only like this:

$('div[style="left: 0px; top:0px;"]');

That being said, it still won't get you the desired result since your inline style would have to match exactly.

To get a bit closer you can use wildcard attribute selector to get part of the inline style like this, though it's really going to be very finicky and so much as a single whitespace will cause this to fail.

$('div[style*="left: 0px; top: 0px"]').html('test345');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="blockattribute" id="1" style="background-color: rgb(217, 217, 217); left: 0px; top: 0px;">test 123</div>

A bit more on this here: https://css-tricks.com/attribute-selectors/#rel-anywhere.