Problem with style precedence when JavaScript modifies DOM nodes

Source: Internet
Author: User

  The xxx style attributes, which are set or read by Element.style.xxx, belong to the inline style (<p style= "color=red" ></p>)and are not Use the link's external CSS file or a style defined in the <style></style> tab

Style Priority: * < TagName < class < ID < inline (inline style is written in tag)

In the following code

Observe the state change of the DIV:

The initial state is <div id= "Div1" ></div> the div interior is white;

First click to turn red, become <div id= "Div1" class= "Red" ></div> at this time div inside is red;

Then click Turn yellow, change to <div id= "Div1" class= "Red" style= "Background-color:yellow;" ></div>, when the inner color of the div changes to yellow, the yellow is the inline style, overwriting the same attribute (Background-color) style set by class or ID.

Refresh the browser to change the order:

The initial state is <div id= "Div1" ></div> the div interior is white;

First click Turn yellow, become <div id= "Div1" style= "Background-color:yellow;" ></div>, when the inner color of the div changes to yellow, the yellow is the inline style

Then click to turn yellow, become <div id= "Div1" style= "Background-color:yellow;" class= "Red" ></div> the div is still yellow inside, This is because the added class attribute priority is not higher than the priority of the inline attribute added in the previous step, so it does not work.

Suggestions:

If this happens, very headache, because no error, so it is difficult to find

So, as much as possible on the same element, change the style attributes, just in one way, or only use element.style.xxx, or just use element.classname= ' xxx '.

Problem with style precedence when JavaScript modifies DOM nodes

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.