Note:

If you want to create a new page for developers, you should create it on the Moodle Developer Resource site.

JavaScript cheat sheet: Difference between revisions

From MoodleDocs
mNo edit summary
Line 21: Line 21:


<code js>
<code js>
// Check if the element has a certain class.
if (e.target.classList.contains('classname')) {
if (e.target.classList.contains('classname')) {
    // Add a new CSS class to the element.
     e.target.classList.add('someclassname');
     e.target.classList.add('someclassname');
    // Remove a CSS class from the element.
     e.target.classList.remove('anotherclassname');
     e.target.classList.remove('anotherclassname');
}
}
</code>
</code>

Revision as of 15:01, 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

// Check if the element has a certain class. if (e.target.classList.contains('classname')) {

   // Add a new CSS class to the element.
   e.target.classList.add('someclassname');
   // Remove a CSS class from the element.
   e.target.classList.remove('anotherclassname');

}