DOM element manipulation

Introduction to DOM

The Document Object Model (DOM) is a standard programming interface for processing extensible markup languages ​​(HTML or XML) recommended by the W3C organization . W3C has defined a series of DOM interfaces through which the content, structure and style of web pages can be changed .
DOM tree related concepts: The
dom tree is a tree structure that describes the structure of the document according to the document before the browser renders the page during the process of loading the web page document.
Insert picture description here

  • Document : A page is a document, which is represented by document in the DOM.
  • Element : All tags in the page are elements, which are represented by element in the DOM.
  • Node : All content in a web page is a node (labels, attributes, text, comments, etc.), which is represented by node in the DOM.

The above content is regarded as an object in the DOM.

Get element

Before operating an element, you must first obtain the corresponding element before you can operate. The following learn several APIs for obtaining elements.
1. Get elements based on ID

// getElementById('id');方法可以获取带有指定ID的元素对象。
var btn0 = document.getElementById('btn0');

2. Get the element according to the tag name

// getElementsByTagName('标签名');方法可以返回带有指定标签名的对象的集合。
var lis = document.getElementsByTagName('li');
var ols = document.getElementsByTagName('ol');
vat olLis = ols[0].getElementsByTagName('li');

Note:
(1) Because what we get is a collection of objects, we need to traverse if we want to manipulate the elements inside.
(2) The obtained element is dynamic (the content in the pseudo-array will also change if the html structure changes).
(3) If the element cannot be obtained, an empty pseudo-array is returned (because the object cannot be obtained).
(4) When obtaining all the elements with the specified tag name in an element (ancestor element), the ancestor element must be a single element (which element object must be specified, such as document, ols[0] above). The ancestor is not included when obtaining The element itself.

3. Obtained through the new method of HTML5

// 1、getElementsByClassName('类名');方法返回指定类名的元素对象的集合。
var tabItems = document.getElementsByClassName('tab_item');
// 2、querySelector('选择器');返回与指定选择器相匹配的第一个元素对象。
var btn0 = document.querySelector('#btn0');
var current = document.querySelector('ul li.current');
// 3、querySelectorAll('选择器');返回与选择器匹配的所有元素对象的集合。
var lis = document.querySelectorAll('ul li');

Note: The selector parameters in querySelector and querySelectorAll need to add selector designation symbols.

4. Get special elements (body html)

var bd = document.body; // 返回body元素对象
var htmlEle = document.documentElement; // 返回html元素对象

Event basis

javascript enables us to create dynamic pages, and events are behaviors that can be detected by javascript . After the javascript event is detected (triggered), it can respond (execute the event handler) . Every event in the web page can generate certain events that can trigger javascript. For example, we can generate an event when the user clicks a button, and then perform certain operations we set; a single user clicks on the link (if we don’t have Do any other processing) will jump to the corresponding page or anchor point, this is the default operation (behavior).
In the basic part of events, we only need to know about events. What we need to pay attention to when programming is the three elements of events and simple binding (registering) events for elements.
The three elements of the event:

  1. Event source , before binding the event, you must specify which element object you want to bind the event to.
  2. Event type , what event should be bound to the event source in order to meet the requirements (for example: mouse click or move in, keyboard press or pop up, etc.).
  3. Event handler , what operations the program will perform when it occurs (after the event is triggered).

Simple event binding syntax:

var btn = document.getElementById('btn');
btn.onclick = function() {
    
    
	console.log('已经为按钮绑定好点击事件');
}
// 事件源btn;事件类型鼠标点击;事件处理程序function(){}的内部处理语句。

Learn more about javascript events.

Operation element

JavaScript's DOM operation can change the content, structure and style of web pages. We can use DOM operation elements to change the content and attributes of the elements. The following are all attributes .

Change element content

The attributes that change or get the content of an element are: innerText, innerHTML

<body>
    <div class="test">您的名字:<span>扬尘</span></div>
</body>
	// 1、innerText获取元素的文本内容(只会获取文本节点)
	var div = document.querySelector('.test');
    console.log(div.innerText); // ->您的名字:扬尘
    // 2、innerHTML获取元素的全部内容(包含所有的节点)
    console.log(div.innerHTML); // ->您的名字:<span>扬尘</span>
    // 3、修改内容
    div.innerHTML = '我的名字:<sapn>不告诉你</span>';
    div.innerText = '拉倒'; 
    // 注意:innerText不能识别其他节点类型,如果有标签也是直接显示出来
Attribute manipulation

Attribute operations of common elements

  1. innerText, innerHTML change the content of the element.
  2. src、herf
  3. id、alt、title

Attribute manipulation of form elements

  1. type : Change the form type.
  2. value : Change the value (content) of the form.
  3. checked : Change the checked attribute of the check box (or radio button) option.
  4. selected : Change the selected attribute in the drop-down single-select element option.
  5. disabled : Change the attribute of whether the form control is disabled.
Style attribute manipulation

We can modify the size, color, position and other attributes of the element through js. The style attribute and className attribute are used.

// style属性进行的是行内样式操作(实际上是添加了行内样式或改变了元素的行内样式属性style)
var div = document.querySelector('div');
div.style.fontSize = '12px';
div.style.backgroundColor = 'red';
// 实际上是给文档中的div元素添加或者改变了style属性。
// 比如:原<div style="color:yellow;font-size:16px;" 
// 	现<div style="font-size:12px;background-color:red;"

note:

  1. The attribute value must be quoted (in the form of a string), no matter what the value is.
  2. The attribute name adopts the small hump naming method
// className属性进行的是类名样式操作,即将元素的类属性进行修改。
// 在css样式文件中不同的类设置有不同的样式,因此也就达到了修改样式的目的。
div.className = 'current';
div.className = '';

If there are many modified styles, you can change the element style by operating the class name.
class is a reserved word so use className to manipulate element class name attributes.
className will directly change the class name of the element and will overwrite the original class name.

Style attribute manipulation

The reason why this attribute is recorded separately is because it is a new attribute of h5, which has poor compatibility and is supported by browsers above ie10. But it feels very practical, so I probably remembered it.

// 可以返回元素具有的类名列表
var div = document.querySelector('div');
console.log(div.classList[1]);
// 以追加的形式给元素添加类名(不会覆盖以前具有的类名)
div.classList.add('newClassName');
// 删除某个类名
div.classList.remove('targetClassName');
// 切换类名,如果具有就删除,如果没有就添加
div.classList.toggle('xxclass');
Custom attribute operation

Custom attributes are some attributes that we customize to indicate certain information . For example, in the tab column, we set an index attribute for each li in order to identify which column we selected. This type of attribute is to save and use data, some data can be saved to the page without saving to the database.
1. Get the attribute value

  • element.属性; Get the value of the built-in attribute, this method cannot get the value of the custom attribute.
  • element.getAttribute('属性'); The value of the method can be obtained regardless of whether it is an inherent attribute or a custom attribute (mainly used to obtain custom attributes).

2. Set the attribute value

  • element.属性 = '值'; Used to set the value of a built-in attribute.
  • element.setAttribute('属性名','值'); Mainly set custom attributes (standard).

3. Remove attributes

  • element.removeAttribute('属性'); Remove custom attributes.

4. Some custom attributes are easy to cause ambiguity, and it is not easy to judge whether it is a built-in attribute or a custom attribute of the element. H5 stipulates some new usage rules for this purpose.

  • The custom attribute data- begins as the attribute name and assigns a value. For example: <div data-index="1"></div> or element.setAttribute('data-index',2).
  • Acquisition can be used element.getAttribute('data-index'); H5 can also use the new way element.dataset.indexor element.dataset[index]to get, but ie11 began to support.

Guess you like

Origin blog.csdn.net/TKOP_/article/details/113173455
Recommended