{"id":22005317,"url":"https://github.com/anish000kumar/javascript-dom-api-cheatsheet","last_synced_at":"2026-04-01T20:21:57.837Z","repository":{"id":91824856,"uuid":"158106556","full_name":"anish000kumar/Javascript-DOM-API-cheatsheet","owner":"anish000kumar","description":null,"archived":false,"fork":false,"pushed_at":"2021-02-17T09:56:33.000Z","size":20,"stargazers_count":221,"open_issues_count":0,"forks_count":59,"subscribers_count":6,"default_branch":"master","last_synced_at":"2025-04-09T15:58:57.554Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/anish000kumar.png","metadata":{"files":{"readme":"readme.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null}},"created_at":"2018-11-18T17:01:27.000Z","updated_at":"2025-02-25T08:09:52.000Z","dependencies_parsed_at":null,"dependency_job_id":"8dd367f6-4f0d-4f2e-9690-743fc5f98f16","html_url":"https://github.com/anish000kumar/Javascript-DOM-API-cheatsheet","commit_stats":{"total_commits":7,"total_committers":2,"mean_commits":3.5,"dds":0.1428571428571429,"last_synced_commit":"d5c931cde3f3dec9c3926bf61e40c2cd1baa9e4f"},"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/anish000kumar%2FJavascript-DOM-API-cheatsheet","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/anish000kumar%2FJavascript-DOM-API-cheatsheet/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/anish000kumar%2FJavascript-DOM-API-cheatsheet/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/anish000kumar%2FJavascript-DOM-API-cheatsheet/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/anish000kumar","download_url":"https://codeload.github.com/anish000kumar/Javascript-DOM-API-cheatsheet/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248161276,"owners_count":21057555,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-11-30T00:19:30.625Z","updated_at":"2026-03-27T04:29:20.229Z","avatar_url":"https://github.com/anish000kumar.png","language":null,"funding_links":[],"categories":[],"sub_categories":[],"readme":"# Accessing DOM Elements\n\n### DOM node overview\n\n![DOM Element Traversal](https://i.ibb.co/H4Bx8KJ/dom.png)\n\n\n```javascript\n// Returns a reference to the element by its ID.\ndocument.getElementById(\"someid\");\n\n// Returns an array-like object of all child elements which have all of the given class names.\ndocument.getElementsByClassName(\"someclass\");\n\n// Returns an HTMLCollection of elements with the given tag name.\ndocument.getElementsByTagName(\"LI\");\n\n// Returns the first element within the document that matches the specified group of selectors.\ndocument.querySelector(\".someclass\");\n\n// Returns a list of the elements within the document (using depth-first pre-order traversal of the document's nodes)\n// that match the specified group of selectors.\ndocument.querySelectorAll(\"div.note, div.alert\");\n```\n\n#### Grab Children/Parent Node(s)\n\n```javascript\n// Get child nodes\nvar stored = document.getElementById(\"someid\");\nvar children = stored.childNodes;\n\n// Get parent node\nvar parental = children.parentNode;\n```\n\n# Create New DOM Elements\n\n```javascript\n// create new elments\nvar newHeading = document.createElement(\"h1\");\nvar newParagraph = document.createElement(\"p\");\n\n// create text nodes for new elements\nvar h1Text = document.createTextNode(\"This is a nice header text!\");\nvar pText = document.createTextNode(\"This is a nice paragraph text!\");\n\n// attach new text nodes to new elements\nnewHeading.appendChild(h1Text);\nnewParagraph.appendChild(pText);\n\n// elements are now created and ready to be added to the DOM.\n```\n\n# Add Elements to the DOM\n\n```javascript\n// grab element on page you want to add stuff to\nvar firstHeading = document.getElementById(\"firstHeading\");\n\n// add both new elements to the page as children to the element we stored in firstHeading.\nfirstHeading.appendChild(newHeading);\nfirstHeading.appendChild(newParagraph);\n\n// can also insert before like so\n\n// get parent node of firstHeading\nvar parent = firstHeading.parentNode;\n\n// insert newHeading before FirstHeading\nparent.insertBefore(newHeading, firstHeading);\n```\n\n---\n\nSuppose you have the following HTML:\n\n```html\n\u003cdiv id=\"box1\"\u003e\u003cp\u003eSome example text\u003c/p\u003e\u003c/div\u003e\n\u003cdiv id=\"box2\"\u003e\u003cp\u003eSome example text\u003c/p\u003e\u003c/div\u003e\n```\n\nYou can insert another snippet of HTML between #box1 and #box2:\n\n```javascript\nvar box2 = document.getElementById(\"box2\");\nbox2.insertAdjacentHTML(\"beforebegin\", \"\u003cdiv\u003e\u003cp\u003eThis gets inserted.\u003c/p\u003e\u003c/div\u003e\");\n\n// beforebegin - The HTML would be placed immediately before the element, as a sibling.\n// afterbegin - The HTML would be placed inside the element, before its first child.\n// beforeend - The HTML would be placed inside the element, after its last child.\n// afterend - The HTML would be placed immediately after the element, as a sibling.\n```\n\n# Add/Remove/Toggle/Check Classes\n\n```javascript\n// grab element on page you want to use\nvar firstHeading = document.getElementById(\"firstHeading\");\n\n// will remove foo if it is a class of firstHeading\nfirstHeading.classList.remove(\"foo\");\n\n// will add the class 'anotherClass' if one does not already exist\nfirstHeading.classList.add(\"anotherclass\");\n\n// add or remove multiple classes\nfirstHeading.classList.add(\"foo\", \"bar\");\nfirstHeading.classList.remove(\"foo\", \"bar\");\n\n// if visible class is set remove it, otherwise add it\nfirstHeading.classList.toggle(\"visible\");\n\n// will return true if it has class of 'foo' or false if it does not\nfirstHeading.classList.contains(\"foo\");\n```\n\n# Using template literals\n\n```html\n\u003cbody\u003e\u003c/body\u003e\n```\n\n```javascript\nfunction render(props) {\n  return `\n            \u003cdiv class=\"container\"\u003e \n                \u003ch1\u003e ${props.name} \u003c/h1\u003e\n            \u003c/div\u003e\n        `;\n}\n\ndocument.body.innerHTML = render(\"John\");\n```\n\n# Other node methods\n\n```javascript\n// Creates newNode as a copy (clone) of node. If bool is true, the clone includes clones of all the child nodes of the original.\n\nnewNode = node.cloneNode(bool);\n\n// Removes the child oldNode from node.\nnode.removeChild(oldNode):\n\n// Replaces the child node oldNode of node with newNode.\nnode.replaceChild(newNode, oldNode)\n\n// Retrieves the value of the attribute with the name attribute\nnode.getAttribute('attribute')\n\n// Sets the value of the attribute with the name attribute to value\nnode.setAttribute('attribute', 'value')\n\n// Reads the type of the node (1 = element, 3 = text node)\nnode.nodeType\n\n// Reads the name of the node (either element name or #textNode)\nnode.nodeName\n\n// Reads or sets the value of the node (the text content in the case of text nodes)\nnode.nodeValue\n```\n\n# Events\n\n## Inline event handling\n\n```html\n\u003ca href=\"site.com\" onclick=\"dosomething();\"\u003eA link\u003c/a\u003e\n```\n\n## DOM on-event handling\n\n```javascript\nwindow.onload = () =\u003e {\n  //window loaded\n};\n\nconst xhr = new XMLHttpRequest();\nxhr.onreadystatechange = () =\u003e {\n  //.. do something\n};\n```\n\n## Using addEventListener()\n\n```javascript\nwindow.addEventListener(\"load\", onLoad);\nwindow.removeEventListener(\"load\", onLoad);\n```\n\n## Custom events\n\n```javascript\n//A CustomEventInit dictionary, having the following fields: \"detail\", optional and defaulting to null, of type any, that is an event-dependent value associated with the event.\nevent = new CustomEvent(typeArg, customEventInit);\n```\n\n### Dispatching\n\n```javascript\nvar event = new Event(\"build\");\n// Listen for the event.\nelem.addEventListener(\n  \"build\",\n  function(e) {\n    /* ... */\n  },\n  false\n);\n// Dispatch the event.\nelem.dispatchEvent(event);\n```\n\n# Date and time\n\n```javascript\n//Sun Nov 18 2018 23:18:58 GMT+0530 (India Standard Time)\nvar d = new Date();\n//1542563338408 miliseconds passed since 1970\nNumber(d);\nDate(\"2017-06-23\"); // date declaration\nDate(\"2017\"); // is set to Jan 01\nDate(\"2017-06-23T12:00:00-09:45\"); // date - time YYYY-MM-DDTHH:MM:SSZ\nDate(\"June 23 2017\"); // long date format\nDate(\"Jun 23 2017 07:45:00 GMT+0100 (Tokyo Time)\"); // time zone\n\nvar d = new Date();\na = d.getDay(); // getting the weekday\n\ngetDate(); // day as a number (1-31)\ngetDay(); // weekday as a number (0-6)\ngetFullYear(); // four digit year (yyyy)\ngetHours(); // hour (0-23)\ngetMilliseconds(); // milliseconds (0-999)\ngetMinutes(); // minutes (0-59)\ngetMonth(); // month (0-11)\ngetSeconds(); // seconds (0-59)\ngetTime(); // milliseconds since 1970\n\nvar d = new Date();\nd.setDate(d.getDate() + 7); // adds a week to a date\n\nsetDate(); // day as a number (1-31)\nsetFullYear(); // year (optionally month and day)\nsetHours(); // hour (0-23)\nsetMilliseconds(); // milliseconds (0-999)\nsetMinutes(); // minutes (0-59)\nsetMonth(); // month (0-11)\nsetSeconds(); // seconds (0-59)\nsetTime(); // milliseconds since 1970)\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fanish000kumar%2Fjavascript-dom-api-cheatsheet","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fanish000kumar%2Fjavascript-dom-api-cheatsheet","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fanish000kumar%2Fjavascript-dom-api-cheatsheet/lists"}