Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to get Inner Elements using chrome console javascript/jquery

Hi I am trying to get Inner Elements using chrome console, but it throwing me an error , Here is my code snippet . Any Workaround will really help me to get elements and automate it. I have attached a screenshot of a common website

When I do this I am getting the list of class element(i.e.swatches-wrap) as an Array.

$$(`.swatches-wrap`);

When I try this its throwing me an error Uncaught TypeError: $$(...)[0].$ is not a function

$$(`.swatches-wrap`)[0].$(`.title`);

Here is the attached screenshot enter image description here

like image 909
Gowtham Avatar asked Feb 19 '26 18:02

Gowtham


1 Answers

$ and $$ are parts of the devtools utility api provided by chrome (https://developers.google.com/web/tools/chrome-devtools/console/utilities)

$ is a shortcut to document.querySelector and returns the first element that matches the query. By default it starts at the root element (body) and the root element can be overridden by providing a second argument.

$$ is a shortcut to [...document.querySelectorAll('some query')] and returns an array of elements that match the query. By default it starts at the root element (body) and the root element can be overridden by providing a second argument.

For your example, this should be a better approach while also serving as an example of how to use the root argument:

$('.title',$('.swatches-wrap'))

Because of how CSS selectors work, the most efficient way to do your example is

$('.swatches-wrap .title')

If you're looking for multiple .title tags inside .swatches-wrap elements:

$$('.swatches-wrap .title').forEach( elem => {
    console.log('found another `.swatches-wrap .title` ', element)
})

It is important to remember that these are utility functions and that they only exist in the chrome console. If you want to use it in your code, you should use the following examples:

document.querySelector('.swatches-wrap .title')

// or for multiple results

[...document.querySelectorAll('.swatches-wrap .title')].forEach( elem => {
    console.log('found another `.swartches-wrap .title` ', element)
})

document.querySelectorAll returns an Array-like object that can be converted into an array by expanding it into a new array. That is what [...<expression>] does

Finally, if you want to get the same $ and $$ utilities in your code, you don't have to use jQuery, you can just put this in your code and use $ and $$ like we did in the examples above:

// $ polyfill
const $ = document.querySelector.bind(document)

// $$ polyfill
const $$ = (selector, root)=>[...document.querySelectorAll(selector,root)]
like image 83
Nemesarial Avatar answered Feb 22 '26 07:02

Nemesarial



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!