Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery Set width !important after variable [duplicate]

$(".mydiv").css('width', $(".image").width());

this code is working, but i want to make this width important, what is the correct way ?

i tried this but it does not worked

$(".mydiv").css('width', $(".image").width()+'!important');

(!important)

like image 285
Muhammed Özdemir Avatar asked Mar 23 '23 07:03

Muhammed Özdemir


2 Answers

The problem is caused by jQuery not understanding the !important attribute, and as such fails to apply the rule.

You might be able to work around that problem, and apply the rule by referring to it, via addClass():

.importantRule { width: 100px !important; }
 $('#mydiv').addClass('importantRule');

Or by using attr():

$('#mydiv').attr('style', 'width: 100px !important');

For reference please go through the below question:- How to apply !important using .css()?

like image 176
Nishant Avatar answered Apr 10 '23 01:04

Nishant


Just try this

        var previousStyle = $(".mydiv").attr('style')
        $(".mydiv").attr('style', 'width:' + $(".image").width() + '!important; ' + previousStyle + '');

Important Attribute $(document).ready(function () { var previousStyle = $(".mydiv").attr('style') $(".mydiv").attr('style', 'width:' + $(".image").width() + '!important; ' + previousStyle + ''); }) check

<html>
<head>
    <title>Important Attribute</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () { 
            var previousStyle = $(".mydiv").attr('style')
            $(".mydiv").attr('style', 'width:' + $(".image").width() + '!important; ' + previousStyle + '');
        })
    </script>
</head>
<body>
    <div class="mydiv" style="border: 1px solid black; width: 200px">check</div>
    <div class="image" style="width: 280px"></div>
</body>
</html>

if you inspect and see the mydiv attributes you can see the width and important tag, as stated from the jquery statement

like image 45
Raghurocks Avatar answered Apr 10 '23 02:04

Raghurocks