I have HTML like this:
…
<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 like this:
var pos = { top: 252, left: 54 };
I want to select the element with the position that the object literal indicates. Positions are unique, so only one element will be selected.
Thank you for answers.
The [attribute|="value"] selector is used to select elements with the specified attribute, whose value can be exactly the specified value, or the specified value followed by a hyphen (-). Note: The value has to be a whole word, either alone, like class="top", or followed by a hyphen( - ), like class="top-text".
[attribute$=”value”] Selector: This selector is used to select all the elements whose attribute value ends with the specified value. The value doesn't need to be a whole word. [attribute*=”value”] Selector: This selector selects all the elements whose attribute value contains the specified value present anywhere.
The [attribute=value] selector is used to select elements with the specified attribute and value.
The attr() CSS function is used to retrieve the value of an attribute of the selected element and use it in the stylesheet. It can also be used on pseudo-elements, in which case the value of the attribute on the pseudo-element's originating element is returned.
Credit goes to the original poster here;
jQuery find by inline css 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;
}
});
You can then search elements by their style attribute values using your new jquery extensions function such as;
$("div:styleEquals('top=252px'):styleEquals('left:54px')");
All I can say is don't do this!
If you can add a unique position style to a div, you can equally easily add an identifier at the same time.
Use this identifier to select the element in javascript, not the css positioning.
You can do it like this with 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 need to make sure to use white space consistently. 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 by using my example code, and the order would not matter. Here is an example:
<div style="left: 54px; background: gray; top: 252px;"></div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With