Created
August 3, 2017 14:43
-
-
Save himalay/4e08103181e141c542c30f4ebafb50d4 to your computer and use it in GitHub Desktop.
Useful DOM methods
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| tinyurl.com/domfitc | |
| //// Insert elements | |
| el.insertAdjacentHTML(<location>, <HTML string>); | |
| // locations | |
| <!-- beforebegin --> | |
| <div> | |
| <!-- afterbegin --> | |
| <p>some text</p> | |
| <!-- beforeend --> | |
| </div> | |
| <!-- afterend--> | |
| //// Get location of an element in the screen | |
| el.getBoundingClientRect(); | |
| // returns object with height, width, top, bottom, left and right | |
| //// Access data attribute in dom | |
| <div data-my-data="old"></div> | |
| el.dataset.myData;// old | |
| el.dataset.myData = 'new'; | |
| el.dataset.myData;// new | |
| //// Which target event | |
| <div id="parent"> | |
| <div id="children"></div> | |
| </div> | |
| parentEl.addEventListener('click', e => { | |
| console.log(e.target); | |
| console.log(e.currentTarget); | |
| }); | |
| //// if element has attribute/attributes | |
| <p id='myId'>some text</p> | |
| <p>some more text</p> | |
| firstEl.hasAttribute('id');// true | |
| firstEl.hasAttributes();// true | |
| secondEl.hasAttribut('id');// false | |
| secondEl.hasAttributs();// false | |
| //// child nodes | |
| <ul id="myList"> | |
| <like class="one">one</li> | |
| <li>two</li> | |
| <li>three</li> | |
| <li class="four">four</li> | |
| </ul> | |
| myListEl.childElementCount;// 4 | |
| myListEl.firstElementChild.className;// one | |
| myListEl.lastElementChild.className;// four | |
| // this doesn't include text and whitespace nodes unlike el.firstChild(); | |
| //// if a DOM node contains in another DOM node | |
| <body> | |
| <div id="one"> | |
| <div id="two"> | |
| <div id="three"></div> | |
| </div> | |
| </div> | |
| <div id="xyz"></div> | |
| </body> | |
| oneEl.contains(twoEl);// true | |
| oneEl.contains(xyzEl);// false | |
| bodyEl.contains(threeEl);// true | |
| twoEl.contains(oneEl);// false | |
| //// if two DOM nodes are equal | |
| <body> | |
| <!-- comment --> | |
| <div class="xyz"></div> | |
| <div class="xyz" id="stuff"></div> | |
| <!-- comment --> | |
| <body> | |
| let nodes = document.body.childNodes; | |
| nodes[0].isEqualNode(nodes[3]);// true | |
| nodes[1].isEqualNode(nodes[2]);// false | |
| //// Get style and pseudo-element | |
| window.getComputesStyle(el); | |
| window.getComputesStyle(el, 'before'); | |
| // doesn't work with :first-letter and :firat-line | |
| //// Get text content of an element | |
| el.textContent; | |
| // or | |
| el.innerText; better with whitespace | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment