After getting HTML elements, we may need to use Javascript to manipulate. This post will introduce: ① How to listen element events? ② How to add or delete child elements? ③ How to change element attributes?
Keywords: HTML elements, Javascript , listen events , add , delete , attributes.
Listen events
We often need to listen to some events of the element to trigger further processing. Usually need to listen : mousedowm, mouseup, mouseover, mouseout and change. The following case is for these events, other events are similar, as long as you know the event name, you can replace the corresponding event name.
listen mouse events
Create elements
To create an element, you can use the document.createElement() method, but this method cannot use this as a parameter when assigning a value to the element click event. In this case, you can use the string method to create the element.
create elements by string
Add/Delete elements
If you want to add or delete elements, you need to get the corresponding node then manipulate it.
Change attributes
To set an element attribute use the setAttribute() method and to remove an attribute use the removeAttribute() method. Among attributes, hidden is a special one. If you want to hide the element, you can set the hidden attribute of the element to true, but if you want show the element, you need to remove the hidden attribute rather than set hidden to false.
Javascript has a lot of element manipulate methods. This post mainly introduces how to use addEventListener() to listen events, how to use document.createElement() to create functions and use this as a parameter, and how to use appendChild() and insertBefore() to add children elements, and finally describes how to add and remove attributes through setAttribute() and removeAttribute().