Select Element By CSS style (all with given style)

前端 未结 4 1215
无人共我
无人共我 2020-12-09 13:44

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

4条回答
  •  Happy的楠姐
    2020-12-09 14:00

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

提交回复
热议问题