简体   繁体   English

如何 select 具有自定义属性的元素?

[英]How to select an element with custom attributes?

I am trying to select this checkbox using Javascript我正在尝试 select 这个复选框使用 Javascript

<input type="checkbox" class="cc_filter_checkbox cc_checkbox" data-specid="a1h02000000L"data-spec="BRAND" data-value="Testval">

the code below works but is not ideal下面的代码有效,但并不理想

const obj = document.querySelector("#collapsea1h02000000L > ul > li:nth-child(2) > div > label > input");

I tried these我试过这些

const obj = $('input[data-value="Testval"]');

$('input[data-value="Testval"]').click();

const obj = document.evaluate("//input[contains(text(),'Testval')]", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;

but they did not work.但他们没有工作。 Any thoughts on how I can get this to work?关于如何让它发挥作用的任何想法?

UPDATED CODE with data-value not hardcoded数据值未硬编码的更新代码

const params = new URLSearchParams(window.location.search);
                       
  if(params.has('brand')) {

     const sel = 'input[data-value="' + param + '"]';
                
     // find the element (checkbox) with the brand name
     const obj = $(sel)[0];  

Using jQuery you can retrieve via data-value.使用 jQuery 您可以通过数据值检索。

 const item = $('input[data-value="Testval"]')[0]; console.log(item.value); item.click();
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="checkbox" class="cc_filter_checkbox cc_checkbox" data-specid="a1h02000000L"data-spec="BRAND" data-value="Testval" value="your-val">

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM