Home > Blockchain >  For any given Dom nod find nods that have css style
For any given Dom nod find nods that have css style

Time:09-22

I am trying to find a way to get all elements that have specified styles on them.

//let's say
 let d = $(document)

There is no way to do d.find or d.filter for all children that have .css('background-image'). The node that has to be searched is always different since it comes from mutation.target.

CodePudding user response:

Use the selector * to find all elements, then use .filter() to test .css() with the style you want.

$(document).find("*").filter(function() {
    return $(this).css('background-image');
});

CodePudding user response:

Try the following example:

var elements = document.querySelectorAll(
    'li[style*="background:red"]'
);

console.log(elements);
<ul>
    <li style="background:red;">test1</li>
    <li style="background:blue;">test2</li>
    <li style="background:green;">test3</li>
    <li style="background:red;;">test4</li>
</ul>

CodePudding user response:

Here is a generic solution that get the elements according it's style property, but every property has it's own structure, for example the background and colore are in rgb() structure, I'll give a simple example on width style property:

const elements = $('li').filter(function() {
    return getComputedStyle(this).width == '100px';
});

console.log('elements: ', elements)
.width-100 { width: 100px; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

<ul>
    <li style="background:red;">test1</li>
    <li style="background:red; width:100px">test2</li>
    <li style="background:red;">test3</li>
    <li class="width-100" style="background:red;">test4</li>
</ul>

  • Related