Ricky
Ricky

Reputation: 35853

How to specify a style not to be overriden by styles specified in JS

I got some elements whose style is dynamically modified by a JS. However, I hope one of which would not be modified.

How could I specify its style, which is static, not to be overriden anyway. Thanks.

Upvotes: 0

Views: 129

Answers (5)

Justin Johnson
Justin Johnson

Reputation: 31300

As you have seen, you can't do this in CSS; however, you can instruct your JavaScript to not update an element's style, but it requires some manual attention. Consider the following:

HTML

<ul id="some-list">
    <li>A</li>
    <li>B</li>
    <li class="no-style-update">C</li>
    <li>D</li>
</ul>

JavaScript (vanilla)

var nodes = document.getElementById("some-list").getElementsByTagName("LI");

for ( var i=0, l=nodes.length; i<l; ++i ) {
    // If style updates are allowed
    if ( !nodes[i].className.match(/\bno-style-update\b/i) ) {
        // Update the element's style
    }
}

Upvotes: 2

BeWarned
BeWarned

Reputation: 2338

Perhaps you could put the elements into an iframe, where the src attribute refers to a different path or domain. The javascript in the container page then couldn't modify the element, because of same origin rule which doesn't allow modification of data from different origins.

Upvotes: -1

Randell
Randell

Reputation: 6170

The short answer is you can't. CSS is applied as it is encountered by the browser. Since the call to the JavaScript is the latest call that changes that particular style, it will be applied to the element.

What you can to is to run another JavaScript that changes the style of that specific element after the first script. Since there is something unique about that element, you can probably refer to it by its ID, class, or name.

Upvotes: 2

GSto
GSto

Reputation: 42350

this cannot be done. JavaScript executes after the CSS has been loaded & applied. you'll have to change your IDs & classes and/or your JavaScript code so that it does not target the elements you don't want changed.

Upvotes: 4

Jason Kester
Jason Kester

Reputation: 6031

You can't.

The best you could do would be to override the javascript methods that do the modifying.

Upvotes: 2

Related Questions