<...">

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.

+6
source share
7 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')"); 
+5
source

All I can say is not to do it!

If you can add a unique position style to the div, you can also easily add an identifier at the same time.

Use this identifier to select an element in javascript, not css positioning.

+5
source

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> 
+2
source

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

+1
source

When you create these DIVs, assign them a unique id attribute. Then you can get a DIV object with id attribute.

+1
source

Give them a class or id and select them using the / id class, it will be much faster. Otherwise, you will need to find them all and filter by css values.

+1
source

you can select an element according to the content of the style attribute (note the spaces):

 $('div[style*="top: 252px; left: 54px"]').css("color","red") 

An example .

But, as BonyT said, you have to put the values ​​in id or class.

+1
source

Source: https://habr.com/ru/post/893578/


All Articles