简体   繁体   中英

How refresh the style of an HTML element after changing it using Javascript?

I have an HTML page containing XML. Using Javascript, the XML attributes can be changed when the user clicks a button. (So far, everything works)

However, the attribute that is changed is used in the linked CSS to determine the background color of the element. When the attribute value is changed, the style is not refreshed, so the color doesn't change.

I can alter the javascript to also change the color, but that would involve hardcoding the color, and partially defeat the point of using CSS.

So, it seems to me, I need to do one of two things, and I can't figure out how to do either:

  • read the color from the CSS, and then assign it using javascript
  • somehow use javascript to have the CSS re-applied to the document.

Which approach is better? I assume the 2nd is easier, unless there is a side-effect I haven't thought of. And, whichever approach is better, HOW TO DO IT?

My CSS contains:

*[cleared=true] {
background:lightgrey;
}

My XML looks like this:

<Transfer ID="31266" Date="2015-04-14" Cleared="false">
    <AccountCharge Account="Unplus">-826.20</AccountCharge>
    <AccountCharge Account="Amex">826.20</AccountCharge>
    <TransactionID>1504140662984782</TransactionID>
</Transfer>

My Javascript is:

function Reconcile(Element_ID){
try {
    var c=document.getElementById(Element_ID);
    c.setAttribute('Cleared','True');
    }
catch(e) {
    alert(e.description);
    }
}

I have tried changing the script from modifying 'Cleared' to 'Date', and I can see the date change. The 'Cleared' attribute is not displayed directly by the CSS, but is used to set the formatting of other elements and/or attributes.

Changing the value of 'Cleared' before the page is loaded has the effect I expect - the CSS causes the formatting I expect. However, after the page is loaded, when the javascript changes the value of 'Cleared', no visible change in formatting takes place.

Did you try to assign classes?

Either with pure Javascript:

document.getElementById('selector').className = 'active';

or with jQuery:

jQuery('#selector').addClass('active') ;

This way you can use CSS classes and not hardcode the colour in your Javascript code.


See implementation of addClass and removeClass in Javascript: http://jaketrent.com/post/addremove-classes-raw-javascript/

There's some info about changing style of HTML element with jQuery: jQuery changing style of HTML element

There's some more if you change your mind: How to modify STYLE attribute of element with known ID using JQuery

You can either add some extra styles or just switch the target class/id.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM