Last active
May 9, 2024 06:49
-
-
Save Offirmo/0c90059e8a99d6e0f6b93d6876fa96ec to your computer and use it in GitHub Desktop.
[DOM manipulation: WRITING] #JavaScript #dom #browser #frontend
This file contains 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
// http://youmightnotneedjquery.com/ | |
// navigating | |
// This works in all browsers: | |
location.assign('...') | |
location.href = '...' | |
location = '...' | |
location.reload() | |
// If you wanted to change the page without it reflecting in the browser back history, you can do | |
location.replace('...') | |
element.click() | |
// set id | |
elt.setAttribute('id', 'foo'); | |
// change a CSS variable | |
document.documentElement.style.setProperty( | |
'--omr⋄ui__bottom-menu--selected-reverse-index', | |
css_selected_bottom_menu_value, | |
) | |
/// change classes | |
const body_elt = document.getElementsByTagName('body')[0] | |
body_elt.classList.add('o⋄top-container', 'foo') | |
body_elt.classList.remove('sb-show-main', 'sb-main-padded') | |
/// change data attribute | |
// https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes | |
const body_elt = document.getElementsByTagName('body')[0] | |
body_elt.dataset['oTheme'] = 'light-on-dark' // -> data-o-theme="light-on-dark" | |
//body_elt.dataset['o-theme'] = 'light-on-dark' // NOOOO! There is a crazy camelcase going on | |
// show/hide an element | |
document.getElementById('fieldFirstLastName').style.display = 'block'; // 'none' | |
panelBodyElement.style.display = 'flex' | |
panelBodyElement.style['flex-direction'] = 'column' | |
// Inject html | |
document.getElementById('1') | |
.insertAdjacentHTML('beforebegin', '<div id="0.9"></div>'); | |
afterbegin, beforeend, afterend | |
// create an element beforehand | |
// https://stackoverflow.com/a/494348/587407 | |
const div = document.createElement('div') | |
div.classList.add('gridⵧsquare') | |
div.innerHTML = `<li>text</li>` // HTML string | |
document.body.appendChild(div) | |
// Rewrite the URL | |
const search_params = new URLSearchParams() | |
search_params.append('foo', '42') | |
const new_url = | |
location.origin | |
+ location.path | |
+ '?' + search_params // + location.search | |
+ location.hash | |
if (location.href !== new_url) | |
location.replace(new_url) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment