Brian K Brian K - 21 days ago 4
CSS Question

Using jquery to select an element by it's style

I am trying to select an html element that has no classes or id's, but I still need to select it. Here is what the element looks like:

<table style="background-color: white; border: 1px solid #aaa;
box-shadow: 2px 2px 2px rgba(0, 0, 0, 0.2); border-left: 10px solid
#1E90FF; margin: 0 auto;" class="">


I tried to make a selector that got the element like this:

$("table[style~='background-color: white; border: 1px solid #aaa;
box-shadow: 2px 2px 2px rgba(0,0,0,0.2); border-left: 10px solid
#1E90FF; margin: 0 auto;']")


But it doesn't work. Can someone help me out with this?

Answer

The selector is just wrong, you are missing some spaces.

You can use the attribute selector in jQuery for style but have in mind that an inline-style can change if another javascript function affects the element style the selector will not work.


Looking for another selector is much better, look for a class or an id wrapping the table element.

If there is, do something like this:

.el table {}
OR
#el table {}

Using Attribute selector:

console.log($('table[style="background-color: white; border: 1px solid #aaa; box-shadow: 2px 2px 2px rgba(0, 0, 0, 0.2); border-left: 10px solid #1E90FF; margin: 0 auto;"]').length);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table style="background-color: white; border: 1px solid #aaa; box-shadow: 2px 2px 2px rgba(0, 0, 0, 0.2); border-left: 10px solid #1E90FF; margin: 0 auto;"></table>


Using filter() method

console.log($('table').filter('[style="background-color: white; border: 1px solid #aaa; box-shadow: 2px 2px 2px rgba(0, 0, 0, 0.2); border-left: 10px solid #1E90FF; margin: 0 auto;"]').length);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table style="background-color: white; border: 1px solid #aaa; box-shadow: 2px 2px 2px rgba(0, 0, 0, 0.2); border-left: 10px solid #1E90FF; margin: 0 auto;"></table>

Comments