skip to Main Content

I have a html page generated from a backend, so that I cannot edit anything in this page.

The page doesn’t have any id or class name, but it has inline style inside <div>.

I use Jquery to select DIVs which have style="width: 50%;" and apply a red color to its text.

I have tried couple ways, but somehow it doesn’t work as expected.

Please give me a hand. Thanks!

$(function(){
    if ( $('div').css('width') == '50%;') {
        $('div').css('color', 'red')
    }
     /*  if($('div').is('[style="width: 50%;"]')) {
        $(this).css('color', 'red')
      } */
 })
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div style="width: 50%;">
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
</div>
<div style="width: 90%;">
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
</div>
<div style="width: 50%;">
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
</div>

<div style="position: relative;">
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
</div>

2

Answers


  1. You can use the Attribute-Contains Selector for style:

     $(function () {
            $('div[style*="width: 50%"]').css("color", "red");
     });
    

    Jquery Reference:
    https://api.jquery.com/attribute-contains-selector/

    Login or Signup to reply.
  2. Try using the Attribute-Contains Selector:

     $(function () {
            $('div[style*="width: 50%"]').css("color", "red");
     });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div style="width: 50%;">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
    </div>
    <div style="width: 90%;">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
    </div>
    <div style="width: 50%;">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
    </div>
    
    <div style="position: relative;">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
    </div>
    
     
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search