【问题标题】:Trying to get Inner Elements using chrome console javascript/jquery尝试使用 chrome 控制台 javascript/jquery 获取内部元素
【发布时间】:2019-12-10 07:23:47
【问题描述】:

您好,我正在尝试使用 chrome 控制台获取内部元素,但它抛出了一个错误,这是我的代码 sn-p。任何解决方法都将真正帮助我获取元素并将其自动化。我附上了一个常用网站的截图

当我这样做时,我将类元素列表(即swatches-wrap)作为数组获取。

$$(`.swatches-wrap`);

当我尝试这个时,它给我一个错误Uncaught TypeError: $$(...)[0].$ is not a function

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

这是附件截图

【问题讨论】:

  • 里面没有title
  • 我检查了可用的课程,仍然给我一个问题

标签: javascript jquery google-chrome protractor google-chrome-console


【解决方案1】:

$(".swatches-wrap")[0].querySelector(".info")

  • 返回第一个找到的元素

  • 如果找不到则返回null

你也可以链接它,除非它是null:

$(".swatches-wrap")[0].querySelector(".info").querySelector(".something")

【讨论】:

    【解决方案2】:

    $$$ 是 chrome (https://developers.google.com/web/tools/chrome-devtools/console/utilities) 提供的 devtools 实用程序 api 的一部分

    $document.querySelector 的快捷方式,并返回与查询匹配的第一个元素。默认情况下,它从根元素 (body) 开始,并且可以通过提供第二个参数来覆盖根元素。

    $$[...document.querySelectorAll('some query')] 的快捷方式,并返回与查询匹配的元素数组。默认情况下,它从根元素 (body) 开始,并且可以通过提供第二个参数来覆盖根元素。

    对于您的示例,这应该是一种更好的方法,同时也可以作为如何使用 root 参数的示例:

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

    由于 CSS 选择器的工作原理,最有效的示例方法是

    $('.swatches-wrap .title')
    

    如果您要在 .swatches-wrap 元素中查找多个 .title 标签:

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

    请务必记住,这些是实用功能,并且它们仅存在于 chrome 控制台中。如果你想在你的代码中使用它,你应该使用下面的例子:

    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 返回一个类似数组的对象,可以通过将其扩展为新数组来将其转换为数组。这就是[...<expression>] 所做的

    最后,如果你想在你的代码中获得相同的$$$ 实用程序,你不必使用jQuery,你可以把它放在你的代码中并使用$$$就像我们在上面的例子中所做的那样:

    // $ polyfill
    const $ = document.querySelector.bind(document)
    
    // $$ polyfill
    const $$ = (selector, root)=>[...document.querySelectorAll(selector,root)]
    

    【讨论】:

      【解决方案3】:

      也许你可以试试

      $($(".swatches-wrap")[0]).children(".title")
      

      有什么不同(以堆栈页面为例):

      1. 如果你使用这个↓,会得到一个DOM。

        $(".li")[0]

      2. 如果你使用这个↓,会得到一个Object。

        $(".-img _glyph")

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-04-18
        • 2021-09-24
        • 1970-01-01
        • 1970-01-01
        • 2015-12-31
        • 1970-01-01
        • 1970-01-01
        • 2012-01-08
        相关资源
        最近更新 更多