JS get element styles include non-inline styles

Source: Internet
Author: User

var Obj=document.getelementbyid ("id");

As a result of the new version of JS release, more and more people like to use native JS instead of jquery to manipulate DOM elements, then if through JS to get the style of DOM elements, A lot of people know how to use obj.style this way, but this way can only get Dom inline style, once we define class, and then write in the CSS file will not be obtained, the following I mainly introduce to get inline style and get non-inline style two methods of obtaining.

1, gets the inline style.

<div style= "width:200" id= "id" >asd</div>

Direct use of Obj.style. " Attribute name ", for example obj.style.width can be obtained 200;

If you do not know what the property is called, you can print the DOM object Console.dir (obj); You can see all the attributes in the style on the Web page, which you can manipulate and read.

2, get non-inline style

. test{

height:200px;

}

<div style= "width:200" class= "test" id= "id" >asd</div>

In this example, if the value we get with obj.style.height will be empty,

A) in IE, we use the Currentstyle method of obj to obtain. obj.currentstyle["Height"].

b) in non-IE browsers, we need to use the window's own method, getComputedStyle (obj). Height;

So we can get the element attributes by JS

  

JS get element styles include non-inline styles

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.