felix001
felix001

Reputation: 16691

Css / Jquery Div Style

I have a div that i have added a border style to. However when I try to add a CSS class to it the div style over rides it.

if ($("#input-whatmask").val() != '')
        {
            if(!searchReg.test($("#input-whatmask").val())){
                $("#input-whatmask").addClass("errorinput").after('<span class="error">Enter a valid value.</span>');
                hasError = true;
                return false;
            }
        }

Anyone confirm the correct way / method of doing this ?

Upvotes: 1

Views: 320

Answers (3)

Valli69
Valli69

Reputation: 9902

Do you want like this

if ($("#input-whatmask").val() != '')
{
    if(!searchReg.test($("#input-whatmask").val())){
        $("#input-whatmask").attr("class","errorinput").after('<span class="error">Enter a valid value.</span>');
        hasError = true;
        return false;
    }
}

If you use attr() instead of addClass() then the styles are override. attr() change the oldclass name to newClass name and addClass() just add the newClass to oldClass.

or


use !important for a property which has to be override in newCalss with your same code


or

if ($("#input-whatmask").val() != '')
    {
        if(!searchReg.test($("#input-whatmask").val())){
            $("#input-whatmask").removeClass("oldClass").addClass("errorinput").after('<span class="error">Enter a valid value.</span>');
            hasError = true;
            return false;
        }
    }

Upvotes: 0

Helen
Helen

Reputation: 811

Styles in side the div tag, for example:

<div style="border: 1px solid blue;"></div>

Will override styles from a class attached to the div, for example this div will still have a blue border:

<div class="myClass" style="border: 1px solid blue;"></div>

...

.myClass
{
    border: 1px solid red;
}

However this div will have a red border:

<div class="myClass" style="border: 1px solid blue;"></div>

...

.myClass
{
    border: 1px solid red !important;
}

See this js fiddle: http://jsfiddle.net/jtVRK/

Upvotes: 0

oezi
oezi

Reputation: 51797

i'm sure your problem is because of the css style precedence. a style for an id (#input-whatmask) is more important than one for a class (.errorinput) so nothing will change. to correct that, declare your style as #input-whatmask.errorinput instead of just .errorinput so it will be preferred (id with class is more specific than just id).

to explain how this works exactly (quoting this great article):

Specificity is calculated by counting various components of your css and expressing them in a form (a,b,c,d). This will be clearer with an example, but first the components.

  • Element, Pseudo Element: d = 1 – (0,0,0,1)
  • Class, Pseudo class, Attribute: c = 1 – (0,0,1,0)
  • Id: b = 1 – (0,1,0,0)
  • Inline Style: a = 1 – (1,0,0,0)

An id is more specific than a class is more specific than an element.

Upvotes: 1

Related Questions