Abstract
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.
Here is an example div for every operation
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.
// document.createElement() create element and setting
var this_button= document.createElement('button');
this_button.class="test-btn";
//can not use this as parameter
this_button.onclick=colicThisNode();
// through string create element , can use this as parameter
var parent_button= document.createElement('button');
var outer_html='';
parent_button.innerHTML=outer_html;
var this_button=parent_button.childNodes[0];
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.
var this_div=document.getElementById('example_div');
//remove all childrens
this_div.innerHTML='';
//add childrenNode
var this_button = document.createElement('button');
this_div.appendChild(this_button); //append child as the last node of
this_div.insertBefore(this_button, this_div.children[0]); //append child as the first node of
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.
var this_div=document.getElementById('example_div');
this.setAttribute('hidden','true'); //hide this_div
this..removeAttribute("hidden"); //show this_div
Summarize
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().
Related articles
Coming soon
If yuo have any question or need any help
you can leave a comment or connect me with weichaoxu1998@gmail.com