Some common methods of native JS

JS modifies CSS style
document.getElementById('myid').style.display = 'none';

JS modifies the CLASS property
document.getElementById('myid').className = 'active';

If there are multiple CLASS attributes, separate them with spaces
document.getElementById('myid').className = 'active div-1';

remove all CLASS on this element

document.getElementById('myid').className = '';

Note: Using classList is better than using className

document.getElementById('myid').classList.item(0);//item is the index of the class name

document.getElementById('myid').classList.length;//Read-only property

document.getElementById('myid').classList.add('newClass');//添加class

document.getElementById('myid').classList.remove('newClass');//移除class

document.getElementById('myid').classList.toggle('newClass');//Toggle, remove if there is, add if not

document.getElementById('myid').classList.contains('newClass');//Determine whether the class exists

Supplement: The add and remove methods do not allow chained operations, because all returned undefined, and secondly, it is not allowed to add or delete multiple classes at the same time, you can expand it yourself

 

JS modifies the text
document.getElementById('myid').innerHTML = '123';

 

JS create element and append text to it

var newdiv = document.createElement('div');
var newtext = document.createTextNode('123');
newdiv.appendChild(newtext);
document.body.appendChild(newdiv);
Similarly: removeChild() removes the node, and return node

cloneNode() copies the node

insertBefore() inserts a node (the front of the parent node's content)

 

Note: insertBefore() has two parameters, the first is the inserted node and the second is the inserted position

 

example:

 

  var list = document.getElementById('myList');

 

  list.insertBefore(newItem,list.childNodes[1]);

 

  //Insert the new node newItem to the second child node of the list

 

JS returns all child node objects childNodes
var mylist = document.getElementById('myid');
for(var i=0,i<mylist.childNodes.length;i++){
  console.log(mylist.childNodes[i]);
}

firstChild---return the first child node
lastChild---return the last child node
parentNode---return the parent node object
nextSibling---return the next sibling node object
previousSibling---return the previous sibling node object
nodeName-- - Returns the HTML tag name of the node

 

Source: https://blog.csdn.net/kongjunchao159/article/details/49532403

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324886021&siteId=291194637