How to manipulate HTML elements with pure Javascript?

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().

Edit Template

Leave a Reply

Your email address will not be published. Required fields are marked *

Chaoxu Wei

Master student at Tongji University (Writer & Blogger)

Job hunting, both part-time and full-time jobs are accepted. Job recommendation please email me weichaoxu1998@gmail.com, thank you very much!

0
0
Edit Template

“There are many people in the world who want to work hard but can’t, and people who work too hard and are exhausted. Please don’t use your efforts only to chase your own victory, please use them to help others.”

Follow

Contact

libertynlp@163.com

+86-18385537403

Yangpu District, Shanghai