Select the HTML element by the value of the CSS property in the style attribute
I have such HTML:
β¦ <div style="top: 252px; left: 54px;"></div> <div style="top: 252px; left: 162px;"></div> <div style="top: 288px; left: 108px;"></div> β¦ I have a JavaScript object literal as follows:
var pos = { top: 252, left: 54 }; I want to select an element with a position that indicates an object literal. Positions are unique, so only one item will be selected.
Thanks for answers.
Credit is sent to the original poster here;
jQuery find by css built-in attribute
The function is "styleEquals" and can be implemented as:
jQuery.extend(jQuery.expr[':'], { styleEquals: function(a, i, m){ var styles = $(a).attr("style").split(" ") var found = false; for (var i = 0; i < styles.length; i++) { if (styles[i]===m[3]) { found = true; break; } } return found; } }); Then you can search for elements by their style attribute values ββusing the new jquery extension function, for example:
$("div:styleEquals('top=252px'):styleEquals('left:54px')"); You can do this using the jQuery JavaScript library out of the box:
var pos = { top: 252, left: 54 }; $('div[style*="top: ' + pos.top + 'px"][style*="left: ' + pos.left + 'px"]'); You must use empty space. If you type:
<div style="top:252px; left:54px;"></div> the proposed selector will not work.
You can also add other CSS properties to the style attribute using my sample code, and the order doesn't matter. Here is an example:
<div style="left: 54px; background: gray; top: 252px;"></div> Using
function findElement (top, left) { return target = $('div').filter(function() { var div = $(this); if (parseInt(div.css('top')) == top && parseInt(div.css('left')) == left ) return true; return false; }); } See jsfiddle example