Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use `inspect an element` tool to make global Javascript variable

In the modern browsers (and Firefox + firebug) you can open up your developer tools and either go to the HTML/Elements tab, or you can inspect an element to get an interactive DOM display.

You can do heaps of useful stuff here, and one thing I need to do often is manipulate/interact with a particular element using Javascript (in the console tab).

What I've been doing is using the interactive DOM to add an id attribute like 'bob', then doing whatever I need to do in the console with document.getElementById('bob') (or $('#bob')).

Ideally what I'd like to do is right click on the element and select an option like make JS variable so in the console I can just use a variable called bob,
does anyone know of any such hidden feature/addon/faster method?

like image 425
Hashbrown Avatar asked May 29 '26 15:05

Hashbrown


2 Answers

You can now use the $0 variable in the devtools to get a DoM reference to the last element you selected in the Elements pane.

https://developer.chrome.com/devtools/docs/commandline-api#0-4 print screen

NB This works in Firefox, too!

like image 67
Hashbrown Avatar answered May 31 '26 06:05

Hashbrown


Use the built-in XPath context menu as a shortcut. Here is the process:

  • Right Click on an element from within the DOM Inspector tab
  • Select Copy XPath from the context menu
  • Paste selector into the console
  • Enclose the selector in single quotes
  • Enclose the selector in the $x() method of the console API
  • Append the array index of the selector match
  • Append the desired property/method reference

    $x('//*[@id="header"]')[0].innerText
    
like image 42
Paul Sweatte Avatar answered May 31 '26 05:05

Paul Sweatte



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!