JavaScript DOM
JavaScript DOM
JavaScript DOM
This covers the JavaScript Document Object Model (DOM) Cheatsheet and shows you
how to manipulate DOM elements effectively.
Selecting elements
• getElementById() – select an element by id.
𝐿𝑒𝑡 𝑒𝑙𝑒𝑚𝑒𝑛𝑡 = 𝑑𝑜𝑐𝑢𝑚𝑒𝑛𝑡. 𝑔𝑒𝑡𝐸𝑙𝑒𝑚𝑒𝑛𝑡𝐵𝑦𝐼𝑑(“𝑖𝑑”);
• getElementsByName() – select elements by name.
𝐿𝑒𝑡 𝑒𝑙𝑒𝑚𝑒𝑛𝑡 = 𝑑𝑜𝑐𝑢𝑚𝑒𝑛𝑡. 𝑔𝑒𝑡𝐸𝑙𝑒𝑚𝑒𝑛𝑡𝑠𝐵𝑦𝑁𝑎𝑚𝑒(“𝑛𝑎𝑚𝑒 𝑖𝑛 𝑓𝑜𝑟𝑚”);
• getElementsByTagName() – select elements by a tag name.
𝐿𝑒𝑡 𝑒𝑙𝑒𝑚𝑒𝑛𝑡 = 𝑑𝑜𝑐𝑢𝑚𝑒𝑛𝑡. 𝑔𝑒𝑡𝐸𝑙𝑒𝑚𝑒𝑛𝑡𝑠𝐵𝑦𝑇𝑎𝑔𝑁𝑎𝑚𝑒(“𝑡𝑎𝑔 𝑛𝑎𝑚𝑒”);
• getElementsByClassName() – select elements by one or more class names.
𝐿𝑒𝑡 𝑒𝑙𝑒𝑚𝑒𝑛𝑡 = 𝑑𝑜𝑐𝑢𝑚𝑒𝑛𝑡. 𝑔𝑒𝑡𝐸𝑙𝑒𝑚𝑒𝑛𝑡𝑠𝐵𝑦𝐶𝑙𝑎𝑠𝑠𝑁𝑎𝑚𝑒(“𝑐𝑙𝑎𝑠𝑠 𝑛𝑎𝑚𝑒”);
• querySelector() – select elements by CSS selectors.
𝐿𝑒𝑡 𝑒𝑙𝑒𝑚𝑒𝑛𝑡 = 𝑑𝑜𝑐𝑢𝑚𝑒𝑛𝑡. 𝑞𝑢𝑒𝑟𝑦𝑆𝑒𝑙𝑒𝑐𝑡𝑜𝑟(“. 𝑐𝑙𝑎𝑠𝑠 𝑜𝑟 #𝑖𝑑 ”);
• querySelectorAll() – select elements by CSS selectors.
𝐿𝑒𝑡 𝑒𝑙𝑒𝑚𝑒𝑛𝑡 = 𝑑𝑜𝑐𝑢𝑚𝑒𝑛𝑡. 𝑞𝑢𝑒𝑟𝑦𝑆𝑒𝑙𝑒𝑐𝑡𝑜𝑟𝐴𝑙𝑙(“. 𝑐𝑙𝑎𝑠𝑠 𝑜𝑟 #𝑖𝑑 ”);
Traversing elements
• Get the parent element – get the parent node of an element.
𝐿𝑒𝑡 𝑝𝑎𝑟𝑒𝑛𝑡 = 𝑛𝑜𝑑𝑒. 𝑝𝑎𝑟𝑡𝑒𝑛𝑡𝑁𝑜𝑑𝑒;
• Get child elements – get children of an element.
First child
𝐿𝑒𝑡 𝑓𝑖𝑟𝑠𝑡𝐶ℎ𝑖𝑙𝑑 = 𝑝𝑎𝑟𝑡𝑒𝑛𝑡𝐸𝑙𝑒𝑚𝑒𝑛𝑡. 𝑓𝑖𝑟𝑠𝑡𝐶ℎ𝑖𝑙𝑑;
𝐿𝑒𝑡 𝑓𝑖𝑟𝑠𝑡𝐸𝐿𝑒𝑚𝑒𝑛𝑡𝐶ℎ𝑖𝑙𝑑 = 𝑝𝑎𝑟𝑡𝑒𝑛𝑡𝐸𝑙𝑒𝑚𝑒𝑛𝑡. 𝑓𝑖𝑟𝑠𝑡𝐸𝑙𝑒𝑚𝑒𝑛𝑡𝐶ℎ𝑖𝑙𝑑;
Last child
𝐿𝑒𝑡 𝑙𝑎𝑠𝑡𝐶ℎ𝑖𝑙𝑑 = 𝑝𝑎𝑟𝑡𝑒𝑛𝑡𝐸𝑙𝑒𝑚𝑒𝑛𝑡. 𝑙𝑎𝑠𝑡𝐶ℎ𝑖𝑙𝑑;
𝐿𝑒𝑡 𝑙𝑎𝑠𝑡𝐸𝐿𝑒𝑚𝑒𝑛𝑡𝐶ℎ𝑖𝑙𝑑 = 𝑝𝑎𝑟𝑡𝑒𝑛𝑡𝐸𝑙𝑒𝑚𝑒𝑛𝑡. 𝑙𝑎𝑠𝑡𝐸𝑙𝑒𝑚𝑒𝑛𝑡𝐶ℎ𝑖𝑙𝑑;
All child
𝐿𝑒𝑡 𝐴𝑙𝑙𝐶ℎ𝑖𝑙𝑑 = 𝑝𝑎𝑟𝑡𝑒𝑛𝑡𝐸𝑙𝑒𝑚𝑒𝑛𝑡. 𝑐ℎ𝑖𝑙𝑑𝑁𝑜𝑑𝑒;
Manipulating elements
• createElement() – create a new element.
𝐿𝑒𝑡 𝑒𝑙𝑒𝑚𝑒𝑛𝑡 = 𝑑𝑜𝑐𝑢𝑚𝑒𝑛𝑡. 𝑐𝑟𝑒𝑎𝑡𝑒𝐸𝑙𝑒𝑚𝑒𝑛𝑡(“𝑡𝑎𝑔 𝑛𝑎𝑚𝑒”);
• appendChild() – append a node to a list of child nodes of a specified parent node.
𝑝𝑎𝑟𝑒𝑛𝑡𝑁𝑜𝑑𝑒. 𝑎𝑝𝑝𝑒𝑛𝑑𝐶ℎ𝑖𝑙𝑑(𝑐ℎ𝑖𝑙𝑑𝑁𝑜𝑑𝑒);
• textContent – get and set the text content of a node.
To display
𝑙𝑒𝑡 𝑡𝑒𝑥𝑡 = 𝑛𝑜𝑑𝑒. 𝑡𝑒𝑥𝑡𝐶𝑜𝑛𝑡𝑒𝑛𝑡;
To add
𝑛𝑜𝑑𝑒. 𝑡𝑒𝑥𝑡𝐶𝑜𝑛𝑡𝑒𝑛𝑡 = "𝑛𝑒𝑤𝑇𝑒𝑥𝑡" ;
• innerHTML – get and set the HTML content of an element.
To display
𝑙𝑒𝑡 𝑡𝑒𝑥𝑡 = 𝑒𝑙𝑒𝑚𝑒𝑛𝑡. 𝑖𝑛𝑛𝑒𝑟𝐻𝑇𝑀𝐿;
To add
𝑒𝑙𝑒𝑚𝑒𝑛𝑡. 𝑖𝑛𝑛𝑒𝑟𝐻𝑇𝑀𝐿 = "𝑛𝑒𝑤𝐻𝑇𝑀𝐿";
• DocumentFragment – learn how to compose DOM nodes and insert them into
the active DOM tree.
𝑙𝑒𝑡 𝑓𝑟𝑎𝑔𝑚𝑒𝑛𝑡 = 𝑛𝑒𝑤 𝐷𝑜𝑐𝑢𝑚𝑒𝑛𝑡𝐹𝑟𝑎𝑔𝑚𝑒𝑛𝑡( );
𝑙𝑒𝑡 𝑓𝑟𝑎𝑔𝑚𝑒𝑛𝑡 = 𝑑𝑜𝑐𝑢𝑚𝑒𝑛𝑡. 𝑐𝑟𝑒𝑎𝑡𝑒𝐷𝑜𝑐𝑢𝑚𝑒𝑛𝑡𝐹𝑟𝑎𝑔𝑚𝑒𝑛𝑡( );
• after() – insert a node after an element.
𝑒𝑙𝑒𝑚𝑒𝑛𝑡. 𝑎𝑓𝑡𝑒𝑟(𝑛 𝑛𝑜𝑑𝑒)
• append() – insert a node after the last child node of a parent node.
𝑝𝑎𝑟𝑒𝑛𝑡𝑁𝑜𝑑𝑒. 𝑎𝑝𝑝𝑒𝑛𝑑(𝑛𝑜𝑑𝑒)
• prepend() – insert a node before the first child node of a parent node.