4
$(".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)

1
  • 2
    If it works, why do you want to make it !important? Commented Jul 3, 2013 at 5:30

3 Answers 3

6

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()?

Sign up to request clarification or add additional context in comments.

1 Comment

Problem is ; i do not use 100 px, it is a variable
1

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

6 Comments

This would work in a sense but if the element contained any other information within it it would be all replaced
that is not working :/
that I just tested which is working, now there will not be overwriting of the previous styles also. Hope this helps.
Can you please tell me what is not working?
@Raghurocks i used your code, it does not worked
|
0

you have to change $(".image").width()+'!important' with

$('.image').css('width');

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.