bookmarklet constructor

Costas

Administrator
Staff member
http://js.do/blog/bookmarklets/
https://caiorss.github.io/bookmarklet-maker/

or manually
  • remove all comments
  • copy and paste the code into chrome address bar. chrome will paste it as a single line.
  • copy it back from address bar
  • prepend javascript: to turn it into javascript:<copied_single_line_code>





Web Console Helpers
https://firefox-source-docs.mozilla.org/devtools-user/web_console/helpers/index.html
https://www.tutorialspoint.com/prototype/prototype_utility_methods.htm

querySelector examples
previousSibling ++
firstElementChild document ( can do firstElementChild.click() )

getElementsByTagName document
getElementsByClassName document
getElementById
querySelectorAll document
getElementsByName

childElementCount document
children document
Node.childNodes

Node.nodeType
Node.parentNode (optimize to parentNode.parentNode but better use closest)
Node.parentElement
Element.closest
HTMLElement.offsetParent (explained)

--

JavaScript:
var allElements = document.getElementsByTagName('*'); --HTMLCollection is LIVE
var x = document.getElementsByClassName('red test'); --HTMLCollection

var x = document.getElementById('para'); --NodeList is STATIC
x.childNodes -- is LIVE
var allElements = document.querySelectorAll('body > *'); --NodeList
allElements.childNodes --is LIVE
var x = document.getElementsByName('name_prop_value'); --NodeList
x[0].childNodes --is LIVE
console.log(allElements.childNodes[1]);

reference
https://bobbyhadz.com/blog/javascript-loop-through-all-dom-elements
HTMLCollection vs. NodeList Explained


Immediately-Invoked Function Expression (IIFE)

JavaScript:
//https://stackoverflow.com/a/42489450
//https://benalman.com/news/2010/11/immediately-invoked-function-expression/
//when not IIFE - every function, when invoked, creates a new execution context.
(function(d) {
  ...
}(document));


Visual Reference to CSS Selectors
https://fffuel.co/css-selectors/
 

Costas

Administrator
Staff member
this is an example on how to iterate whole HTML (LIVE)

example based on any article for https://www.theatlantic.com/ finds the main content and display it.

JavaScript:
var allElements = document.querySelectorAll('body > *');

var m = getMaxLength(allElements);          //STATIC
var m2 = getMaxLength(m.childNodes);    //LIVE
var m3 = getMaxLength(m2.childNodes);  //LIVE

document.body.innerHTML = m3.innerHTML;


function getMaxLength(e) {
    var s = 0;
    var sLen = 0;
    var index2 = 0;

    e.forEach(function (element) {

        if (index2 > 0 && element.nodeType == 1 && element.clientHeight > 0) {
            if (sLen < element.textContent.length) {
                sLen = element.textContent.length;
                s = index2;
            }
        }

        index2++;
    })

    //console.log(e[s].clientHeight + " - char length : " + e[s].outerHTML.length);
    return e[s];
}

must see - https://github.com/camsong/You-Dont-Need-jQuery
 

Costas

Administrator
Staff member
If the first character of an identifier is numeric, you need to escape it

JavaScript:
//src - https://stackoverflow.com/a/20306237
//https://mathiasbynens.be/notes/css-escapes

$$("[id='40b6'")[0].textContent

//or
document.querySelector("[id='1']")

//or you can escape and use it
console.log(CSS.escape('1'));
 

Costas

Administrator
Staff member
iterate elements info

JavaScript:
$$('article>.info').forEach(function(e) {

 var h = e.querySelector('a').href;
 var hTitlr = e.querySelector('a').text;

var descr = e.querySelector('.desc').textContent;
console.log(hTitlr + "|" + descr + '|' + h);
});


select with class attribute nth-child *vs* with element type nth-of-type

nth-child
nth-of-type
nth-last-of-type

JavaScript:
<div class="a">
  <div class="b">111</div>
  <div class="b">222</div>
  <div class="b">333</div>
</div>

const el = document.querySelector('.b:nth-child(2)')
console.log(el) //prints <div class="b">222</div>

--
//when add the h2, prints <div class="b">111</div>
<div class="a">
  <h2>test</h2>
  <div class="b">111</div>
  <div class="b">222</div>
  <div class="b">333</div>
</div>

It is not accurate to use n-th-child against classes among child elements that have different class names..
Solution is to use :
document.querySelector('.b:nth-of-type(2)') ////prints <div class="b">222</div>

select with closest, traverses the element and its parents (heading toward the document root)

JavaScript:
//imagine there are 20 blocks of
<tr class="athing" id="33248623">  // using closest return this!
  <td class="title" valign="top" align="right">x</td>
  <td class="votelinks" valign="top">x</td>
  <td class="title"><span class="titleline"><a href="#">WE SELECT THIS</a></span></td>
</tr>

document.querySelectorAll('span.titleline>a').forEach(function(e) {
    trID = e.closest('tr').id;
});

CSS Selectors

JavaScript:
//select element not contains specific class
document.querySelector("li:not([.toexcludeclassname])")

//src - https://stackoverflow.com/a/69602469 | https://stackoverflow.com/a/73446531
//ref - https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors

// contain abc class
const test = "div[class*='abc']"

// contain exact abc class
const test = "div[class~='abc']"

// class begins with abc
const startsAbc = document.querySelectorAll("[class^='abc']")

// class contains abc
const containsAbc = document.querySelectorAll("[class*='abc']")

// contain exact abc & def(case-insensitively)
const test = "div[class~='abc'][class*='DeF'i]"

// contain exact abc but not def(case-insensitively)
const test = "div[class~='abc']:not([class*='DeF'i])"

// class contains white-space separated word exactly matching abc
const wordAbc = document.querySelectorAll("[class~='abc']")

// class ends with abc
const endsAbc = document.querySelectorAll("[class$='abc']")

//remove class from element
<div class="primary visible info">Item</div>

const div =  document.querySelector('div');
div.classList.remove('info');
//or
div.classList.remove('info','primary');

selectror with wildcard - https://stackoverflow.com/a/8714421
JavaScript:
[id^='someId'] will match all ids starting with someId
[id$='someId'] will match all ids ending with someId
[id*='someId'] will match all ids containing someId
 

Costas

Administrator
Staff member
document.cookie

JavaScript:
    //save cookie with max time
    document.cookie = 'lastID=' + trID + '; SameSite=None; Secure;max-age=31536000'
    //read cookie
    var lastID = document.cookie.split('; ').find((row) => row.startsWith('lastID='))?.split('=')[1];
 

Costas

Administrator
Staff member
ShadowRoot

The ShadowRoot interface of the Shadow DOM API is the root node of a DOM subtree that is rendered separately from a document's main DOM tree. reference

src - https://stackoverflow.com/a/74226587
JavaScript:
document.querySelector('macroponent-123').shadowRoot.querySelector('iframe').contentWindow.location.reload();

//be safe by not using selector due random UID like^
//as always the 'macroponent' tag is first
document.querySelector(document.querySelectorAll("body")[0].childNodes[1].tagName).shadowRoot.querySelector('iframe').contentWindow.location.reload();

ref -
Using shadow DOM - ShadowRoot object represents the root of the shadow DOM tree for that element
Shadow DOM as Web Component gristle
 
Top