Répás
Répás

Reputation: 1820

Jquery style checking and finding the element

In my script i'm looking for the DIV which has class .se and has style attribute display: block, and i need the DIV's ID.

My method is wrong :(

var usedse = $(".se"):has(css('display', 'block')).attr("id");

Could you help me please to fix this?

Upvotes: 0

Views: 464

Answers (5)

gnarf
gnarf

Reputation: 106322

You can write a lot of custom logic using .filter()... This will find all <div class='se'> and check that their CSS display property is set to block, returning the id of the first matched element.

var usedse = $("div.se").filter(function() { 
   return $(this).css('display') == 'block';
}).attr("id");

Upvotes: 2

RobertPitt
RobertPitt

Reputation: 57258

This probably be the best way to accomplish this :)

id = $(".se[style*='display:block']").attr("id");

But you would have to think of multiples here, as your using the classes as selectors it usually means theres multiple div elements that your trying to grab, if thats the case, try this way instead

$(".se[style*='display:block']").each(function(){
    //Here you can do what you want to each element
    // use `this` as a selector, for example
    id = this.attr('id');
});

Just a side note: You have to make sure that your selectors are selecting the correct item when it comes down to css, For example

style = $('element').attr('style'); will only return the value form the actual element such as <div style="display:block".

To get the style values from the element that have been set within css you will have to use the selector to filter them out.

http://jsfiddle.net/4jVC8/

You need to make sure you keep in mind that these are separate!

So heres another filter version.

$('div.se').filter(function() {
    return ( $(this).css('display') == 'block');
});

Upvotes: 1

TJ Koblentz
TJ Koblentz

Reputation: 6948

You have a few options.

One thing you could do is the attribute selector which would return all elements with class se and display css property set:

$(".se [style*='display']").attr('id');

Or, you could use the .css() method and actually check the value of a certain css property:

var $possibles = $(".se"), id;
for ($el in $possibles)
    if ($el.css('display') === 'block') id = $el.attr('id');

Can I ask why you are doing this though? I feel like there must be a better way to look at the problem... maybe you should simply put a class on this element (obviously, this may not be possible depending on the exact problem)?

Upvotes: 1

jAndy
jAndy

Reputation: 235962

I'd recommend this:

var usedse = $('.se:visible').attr('id');
    if(usedse) alert(usedse);

Upvotes: 2

Sarfraz
Sarfraz

Reputation: 382606

The syntax you are using is wrong, try this simple way instead:

if ($("div.se").css('display') == 'block') {
   var usedse = $(".se").attr('id');
   alert(usedse);
}

Upvotes: 1

Related Questions