当前位置:网站首页>JS get element
JS get element
2022-06-13 02:02:00 【Code loving ape】
1. according to id Get elements
document.getElementById(“id The value of the property ”);
The return value is an element object , At present id The object of
2. Get the element according to the tag name
document.getElementsByTagName(“ Name of label ”);
The return value is a pseudo array ;
3. according to name The value of the property gets the element
document.getElementsByName(“name The value of the property ”);
The return value is a pseudo array
4. Get elements based on the name of the class style
document.getElementsByClassName(“ Class style name ”);
The return value is a pseudo array
5. Get elements from selector
1.document.querySelector(“ Selectors ”); Available css Medium One Progeny document.querySelector(‘.box .bx’);document.querySelector(‘.box ul’);
The return value is an element object
2.document.querySelectorAll(“ Selectors ”); Available css Medium Multiple Progeny document.querySelectorAll(‘.box li’);
The return value is a pseudo array
summary :
One 、 Memory differentiation method
Elements There is “s”, English means ( Plural form ) So more than one , Of course, the call should be in the form of an array
**Element only one , That is, the only element , No other element is the same as him
**
Empathy : Get elements from selector , With a “all”( More than one ), One without ( only one ). The calling method obviously has an array subscript and a non - subscript
Two 、 Select the subclass of the parent
1. Get the parent class
var obj= Get the parent class ;
2. Use subclass
obj.children[ Subscript ] or obj.child;
3. If two parent boxes ( Namely “.obj1” and “.obj2”) Have the same subclasses (“.same”), But you want to get what you want ".obj1" Of ".same"
First get the parent class :var obj1 = document.querySelector(‘.obj1’);
Getting subclasses :var same1 = obj1.querySelector(‘.same’);
3、 ... and 、 obtain css style 、 Current properties offset( dynamic ) and Element attributes style( change ) scroll and client
1. style obj.style.cssText = ; Equivalent to directly in css Modify the style inside
cssText What is the essence ?
cssText The essence of this is to set up HTML Elemental style Property value .
cssText The advantages of ?
You can add important,style.top=“80px !important” I can't add it
We usually use js Setting the style of the element object will use this form :
var element= document.getElementById(“id”);element.style.width=”20px”;element.style.height=”20px”;element.style.border=”solid 1px red”;
More than one style , A lot of code ; And through JS To overwrite an object's style is a typical process of destroying the original style and reconstructing it , This destruction and reconstruction , Will increase the cost of the browser .
Use cssText:
element.style.cssText=”width:20px;height:20px;border:solid 1px red;”;
In this way, you can try to avoid pages reflow, Improve page performance .
cssText What is the return value ?
cssText There is also a drawback , The previous style is overwritten . Therefore use cssText Should be superimposed to retain the original style . in addition , In some browsers ( such as Chrome), What value do you give him , It just returns what value . stay IE It is more painful in , It formats the output 、 Will capitalize the attribute 、 Will change the attribute order 、 The last semicolon will be removed , such as :document.getElementById(“d1”).style.cssText = “color:red; font-size:13px;”;alert(document.getElementById(“d1”).style.cssText);
stay IE The median is :FONT-SIZE: 13px; COLOR: red
terms of settlement :
Element.style.cssText += ‘;width:100px;height:100px;top:100px;left:100px;’
in addition , This attribute is added with !important Is particularly useful when using inline styles for , such as ,top:80px !important . While using style.top=“80px !important” It can't be added .
2.obj.offset+“ attribute ” and obj.style.+“ attribute ”
understand : Get the element size and position with offset, Change the value of an element with style.“ attribute ” It can be width、heigth、left、top wait
offset+“ attribute ”( Margins and borders )
( No unit ), Understood as current attribute , Is a read-only property , Non assignable
console.log(box.offsetWidth); // Output number .
inline , Embedded , External styles can be obtained , Is a read-only property , Non assignable
1,offsetWidth Actual width of
offsetWidth = width + about padding + about boder
2,offsetHeith The actual height of
offsetHeith = height + Up and down padding + Up and down boder
3,offsetTop Actual width
offsetTop: The current element On the border Outer edge To The most recent parented (offsetParent) On the border 、 The distance from the inner edge . If none of the parents are located , They are to body Top The distance to the left
4,offsetLeft Actual width
offsetLeft: The current element The left margin Outer edge To The most recent parented (offsetParent) The left margin The distance from the inner edge . If none of the parents are located , They are to body Top The distance to the left
style. +“ attribute ”
Get properties and modify properties , Understood as final attribute .
console.log(box.style.width); // No output , Only inline stylesheets can be obtained
When there is output ,( With units ), Not included padding+border, And is a read-write attribute , You can assign
3.obj. client .+“ attribute ” and obj.scroll.+“ attribute ”
One 、clientWidth and clientHeigh 、 clientTop and clientLeft( Margin )
1,clientWidth Actual width of
clientWidth = width+ about padding
2,clientHeigh The actual height of
clientHeigh = height + Up and down padding
3,clientTop Actual width of
clientTop = boder.top( The width of the top border )
4,clientLeft Actual width of
clientLeft = boder.left( The width of the left border )
Two 、scrollWidth and scrollHeight 、 scrollTop and scrollLeft ( Include hidden areas )
1,scrollWidth Actual width
scrollWidth: Gets the true width of the specified label content layer ( Visual area width + The width of the hidden area ).
2,scrollHeight The actual height of
scrollHeight: Gets the true height of the specified label content layer ( Height of visible area + The height of the hidden area )
3,scrollTop
scrollTop : Top of content layer To Distance to the top of the visible area .
The way to keep getting height :
window.addEventListener(‘scroll’, ()=>{var scrollTop = document.documentElement.scrollTop;});
4,scrollLeft
scrollLeft: Left end of content layer To The distance to the left of the visible area .
3、 ... and 、getBoundingClientRect
Used to get the position set of an element relative to the window . There are top, right, bottom, left Equal attribute .
1. grammar : This method has no parameters .
```
rectObject = object.getBoundingClientRect();
```
2. return type :TextRectangle object , Each rectangle has four integer properties ( On , Right , Next , And left ) Rectangle representing the coordinates of , In pixels .
rectObject.top: The distance from the top of the element to the top of the window ;
rectObject.right: The distance from the right side of the element to the left side of the window ;
rectObject.bottom: The distance from the bottom of the element to the top of the window ;
rectObject.left: The distance from the left side of the element to the left side of the window ;
Native js obtain left Values and top Three ways to value
In use js When doing dynamic effects , Usually, you need to get the... In the absolute positioning of the element left and top Property value . For example, make a collision advertisement , Just keep getting elements top and left Property value .
Something to pay attention to : The value element must be set position:absolute Absolute positioning property , To get left value .
** The first method ,** Relatively simple , It's directly through obj.style.left and obj.style.top, But there are limitations , This method can only get the in-line style left and top The attribute value , Can't get style Labels and link Externally referenced left and top Property value .
** The second method read-only ,** You can get all style style , There are compatibility issues , In the standard browser, you can use window.getComputedStyle( object ,null).left Method to get the left and top The attribute value . And in the IE The browser uses obj.currentStyle.left Method to get the property value .
** The third method ,** Use obj.offsetLeft To get the left Property value , use obj.offsetTop To get the top Property value .
Four 、 get attribute (getAttribute)
getAttribute() yes HTML DOM One way , For acquisition HTML Attribute of element ( Such as id,name,type And other custom attributes ). Empathy ,setAttribute()、removeAttribute() All right. HTML Element properties .
边栏推荐
- Top level configuration + cooling black technology + cool appearance, the Red Devils 6S Pro is worthy of the flagship game of the year
- Devaxpress Chinese description -- tdxgallerycontrol object (gallery component)
- Read routing table
- Numpy multidimensional array transpose transpose
- Introduction to Google unit testing tools GTEST and gmoke
- SQLserver2008 拒绝了对对象 '****' (数据库 '****',架构 'dbo')的 SELECT 权限
- Application and examples of C language structure
- [the second day of actual combat of smart lock project based on stm32f401ret6 in 10 days] (lighting with library function and register respectively)
- Matplotlib drawing Chinese garbled code
- Application circuit and understanding of BAT54C as power supply protection
猜你喜欢

uniapp 预览功能

Combining strings and numbers using ssstream
![[the second day of actual combat of smart lock project based on stm32f401ret6 in 10 days] GPIO and register](/img/eb/9bd411be74937371de0bbf3f04267e.jpg)
[the second day of actual combat of smart lock project based on stm32f401ret6 in 10 days] GPIO and register

Detailed understanding of white noise

10 days based on stm32f401ret6 smart lock project practice day 1 (environment construction and new construction)

Sensorless / inductive manufacturing of brushless motor drive board based on stm32

传感器:SHT30温湿度传感器检测环境温湿度实验(底部附代码)

移动IPv6光猫登录的一般ip地址账号与密码,移动光猫变桥接模式

What is the path field—— Competitive advertising

Developer contributions amd Xilinx Chinese Forum sharing - wisdom of questioning
随机推荐
16 embedded C language interview questions (Classic)
Ruixing coffee moves towards "national consumption"
Stm32+ze-08 formaldehyde sensor tutorial
[learning notes] xr872 GUI littlevgl 8.0 migration (display part)
Detailed explanation of C language conditional compilation
Introduction to ROS runtime
[the fourth day of actual combat of stm32f401ret6 smart lock project in 10 days] voice control is realized by externally interrupted keys
Learning notes 51 single chip microcomputer keyboard (non coding keyboard and coding keyboard, scanning mode of non coding keyboard, independent keyboard, matrix keyboard)
Stm32 3*3 matrix key (register version)
Pyflink implements custom sourcefunction
水管工遊戲
Examples of using the chromium base library
Implementation of pointer linked list
6、 Implementation of warehouse out management function
[programming idea] communication interface of data transmission and decoupling design of communication protocol
The first cell of devaxpress CXGRID after inserting a row is in focus editing status
What is the path field—— Competitive advertising
What is Google plus large text ads? How to use it?
Delphi Google API text to speech MP3 file
LabVIEW large project development tools to improve quality