Javascript select div by style

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;']") 

you can’t select an element by it’s style attributes in jquery. do you have any parent elements you can target?

There’s some missing whitespace in your selector in the rgba function. I’d suggest adding that and seeing if it works.

Okay, I didn’t know that you couldn’t select an element based on it’s css. I’ll try to find a parent element that I can select.

Of course you can, that statement is wrong. jQuery accepts any CSS syntax, and using style is an attribute selector.

Modify your style and suddenly your js doesn’t work. please avoid this completely. Find another way to solve your problem.

3 Answers 3

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.

Читайте также:  Home page

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:

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);
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);

Источник

Select Element By CSS style (all with given style)

I would assume it is easier to find elements by style where the style is explicitly declared: the style is non-inherited (such as positioning) the style is not the default (as would be position:static). Solution 1: Credit goes to the original poster here; jQuery find by inline css attribute The function is ‘styleEquals’ and can be implemented as; You can then search elements by their style attribute values using your new jquery extensions function such as; Solution 2: All I can say is don’t do this!

Select Element By CSS style (all with given style)

Is there a way to select all elements that have a given style using JavaScript?

Eg, I want all absolutely positioned elements on a page.

I would assume it is easier to find elements by style where the style is explicitly declared:

  • the style is non-inherited (such as positioning)
  • the style is not the default (as would be position:static).

Am I limited to those rules? Is there a better method for when those rules apply?

I would happily to use a selector engine if this is provided by one (ideally Slick — Mootools 1.3)

EDIT:
I came up with a solution that will only work with above rules.
It works by cycling through every style rule, and then selector on page.
Could anyone tell me if this is better that cycling through all elements (as recommended in all solutions).
I am aware that in IE I must change the style to lowercase, but that I could parse all styles at once using cssText. Left that out for simplicity.
Looking for best practice.

var classes = ''; Array.each(documents.stylesheets, function(sheet)< Array.each(sheet.rules || sheet.cssRules, function(rule)< if (rule.style.position == 'fixed') classes += rule.selectorText + ','; >); >); var styleEls = $$(classes).combine($$('[style*=fixed]')); 

You can keep Mootools, or whatever you use. 🙂

function getStyle(el, prop) < var view = document.defaultView; if (view && view.getComputedStyle) < return view.getComputedStyle(el, null)[prop]; >return el.currentStyle[prop]; > ​function getElementByStyle(style, value, tag)​ < var all = document.getElementsByTagName(tag || "*"); var len = all.length; var result = []; for ( var i = 0; i < len; i++ ) < if ( getStyle(all[i], style) === value ) result.push(all[i]); >return result; > 
var styleEls = $$('*').filter(function(item) < return item.getStyle('position') == 'absolute'; >); 

Or even create a new selector.
got me interested and so here is one ( its my 1st, so its not built for efficiency ) to find elements by css property..

$.expr[':'].css = function(obj, index, meta, stack)< var params = meta[3].split(','); return ($(obj).css(params[0]) == params[1]); >; 

usage : $(‘optionalSelector:css(property,value)’)
will return all elements ( of optionalSelector ) whose property = value

example : var visibleDivs = $(‘div:css(visibility,visible)’);
will return all divs whose visibility is set to visible ( works for the default visibility as well.. )

There is no selector for CSS attributes, so you’re pretty much stuck to looping through each element and checking it’s position. Here’s a jQuery method:

$("*").each(function() < var pos = $(this).css('position'); if(pos == "absolute") < // do something >else if (pos == "relative") < // do something else >>); 

You can use Case statements instead of if/else as well.

Other than this solution, there is no selector per se that can search by CSS attributes (unless they were inline, maybe).

CSS Selectors, The CSS id Selector. The id selector uses the id attribute of an HTML element to select a specific element. The id of an element is unique within a page, so the id selector is used to select one unique element! To select an element with a specific id, write a hash (#) character, followed by the id of the element.

How to select element by order ?

In a div with class product , there are some multi-level elements. These include two images. The first image is the product thumbnail and the second image is the product rating. They both don’t have class and I can’t change the html code. Sometimes, the images is wrapped inside a tag.

I have to select the image product only. It’s the first img that appears by order inside each div.product .

  img 

I tried with first-of-type and first-child but this method ignore children and sub-children. The wrapped image gets ignored. How can I do that without changing the html code ?

div.product img[data-pin-nopin="true"]:nth-child(1)
   img  

Since the first image has property border . You can style by that.

div.product > img:last-child < border-color: red; >div.product > a:last-child img

The first will be applied to the the last-image only if it’s a direct child of the div.product element.
The second will be applied to the image of the last anchor (also — if it’s a direct child of the div.product element).

Here is a working example:

img < border: solid 2px black >div.product > img:last-child < border-color: red; >div.product > a:last-child img

Following @poi, you can also add :not() to style rating image.

/* For Product Image */ .product img[border] < border: 5px solid green; >/* For Rating Image */ .product img:not([border])
 

Select HTML element by CSS property value in style, Use this identifier to select the element in javascript, not the css positioning. Share. Follow edited Jul 26, 2011 at 10:45. answered Jul 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 …

Select HTML element by CSS property value in style attribute

I have a JavaScript object literal like this:

I want to select the element with the position that the object literal indicates. Positions are unique, so only one element will be selected.

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:

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:

When you generate these DIV, assign them with unique id attribute. Then you can retrieve the DIV object with the id attribute.

JQuery Select Elements with a certain CSS, If you are only checking for display: none and other display properties. You could use the CSS selector :visible in your usual jQuery selections, like this: $ (‘.items:visible’) Or to select the hidden elements: $ (‘.items:hidden’) Share. answered Oct 14, 2018 at 0:24. David Lopez.

Источник

Select HTML element by CSS property value in style attribute

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.

you can create a custom selector here is a SO link that will help stackoverflow.com/questions/1180067/…

7 Answers 7

Credit goes to the original poster here;

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.

Ok. Of course I can do it, I just wanted to ask if there is any possibility how to do this with css values.

but why would you want to? css is for styling elements, not identifying them! If you mix the two, you’re creating a potential maintenance nightmare!

I could see why, what if this was some kind of game? And hundreds of elements were created dynamically. It would not make sense to create one separate CSS class for each and every position up front. Then you would have to select individual elements in some way. I have proposed a way to do this with jQuery out of the box.

Источник

Select all elements that have a specific CSS, using jQuery

Hey there, folks: Please read the question before answering! This poor guy got four out of five completely wrong answers.

6 Answers 6

This is a two year old thread, but it was still useful to me so it could be useful to others, perhaps. Here’s what I ended up doing:

var x = $('.myselector').filter(function () < return this.style.some_prop == 'whatever' >); 

not as succinct as I would like, but I have never needed something like this except now, and it’s not very efficient for general use anyway, as I see it.

Thank you, Bijou. I used your solution, but used the jQuery .css instead of pure javascript, like this:

This example would select all elements where the font-family attribute value contains «Futura».

While this works, just note that this is a very heavy operation depending on the DOM size. If you need it only for a section of the page, then constraint the scope to that. If you need this for the entire page, then you probably need to change this at the css level and not through JS.

You cannot (using a CSS selector) select elements based on the CSS properties that have been applied to them.

If you want to do this manually, you could select every element in the document, loop over them, and check the computed value of the property you are interested in (this would probably only work with real CSS properties though, not made up ones such as rounded ). It would also would be slow.

Update in response to edits — group selectors:

@RobertHarvey — Yes it is. Note that in paragraph 1 I qualify the impossibility of it with «using a CSS selector». Paragraph 2 describes a work around. The linked to question has a number of answers, but the ones with positive voting scores are examples of the work around I described.

Источник

Оцените статью