JavaScript cheat sheet: Difference between revisions
From MoodleDocs
David Mudrak (talk | contribs) (Starting this page as kind of personal cheat sheet of useful snippets as I am getting familiar with ES6 and un-learning YUI and jQuery style of doing things.) |
David Mudrak (talk | contribs) mNo edit summary |
||
Line 16: | Line 16: | ||
// Find the closest parent element matching the selector. | // Find the closest parent element matching the selector. | ||
let region = widget.closest('[data-region]'); | let region = widget.closest('[data-region]'); | ||
</code> | |||
=== CSS classes === | |||
<code js> | |||
if (e.target.classList.contains('classname')) { | |||
e.target.classList.add('someclassname'); | |||
e.target.classList.remove('anotherclassname'); | |||
} | |||
</code> | </code> |
Revision as of 15:00, 29 October 2020
Locating DOM elements
// Get element by identifier.
let root = document.getElementById('uniqueidentifier');
// Get element within another element by attribute.
let widget = querySelector('[data-widget="widgetname"]');
// Find all elements within another element and do something with them.
let missingItems = root.querySelectorAll(':scope [data-region="itemname"].missing');
missingItems.forEach(item => {
window.console.log(item);
});
// Find the closest parent element matching the selector.
let region = widget.closest('[data-region]');
CSS classes
if (e.target.classList.contains('classname')) {
e.target.classList.add('someclassname');
e.target.classList.remove('anotherclassname');
}