【问题标题】:How to select html elements where id contains如何选择id包含的html元素
【发布时间】:2020-05-27 03:12:05
【问题描述】:

如何选择 id 包含给定字符串的 html 元素? querySelectorAll 会做到这一点吗?我知道我可以使用 querySelectorAll 选择类、ID、属性等,

只是不确定我需要做什么的正确方法

这是一些我想只获取 id 包含 Home 的元素的代码

<div id="ContactContainer>
    <input class="form-control input-sm clear" is-required="false" validate-number="" minlength="1" maxlength="3" id="txtCustomerWorkAreaCode" placeholder="9999">
    <input class="form-control input-sm clear" is-required="false" validate-number="" minlength="1" maxlength="3" id="txtCustomerWorkExchange" placeholder="9999">
    <input class="form-control input-sm clear" is-required="false" validate-number="" minlength="4" maxlength="4" id="txtCustomerWorkSuffix" placeholder="9999">


    <input class="form-control input-sm clear" is-required="false" validate-number="" minlength="1" maxlength="3" id="txtCustomerHomeAreaCode" placeholder="9999">
    <input class="form-control input-sm clear" is-required="false" validate-number="" minlength="1" maxlength="3" id="txtCustomerHomeExchange" placeholder="9999">
    <input class="form-control input-sm clear" is-required="false" validate-number="" minlength="4" maxlength="4" id="txtCustomerHomeSuffix" placeholder="9999">


    <input class="form-control input-sm clear" is-required="false" validate-number="" minlength="1" maxlength="3" id="txtCustomerMobileAreaCode" placeholder="9999">
    <input class="form-control input-sm clear" is-required="false" validate-number="" minlength="1" maxlength="3" id="txtCustomerMobileExchange" placeholder="9999">
    <input class="form-control input-sm clear" is-required="false" validate-number="" minlength="4" maxlength="4" id="txtCustomerMobileSuffix" placeholder="9999">
</div>

【问题讨论】:

  • imo 你最好为此添加类。
  • document.querySelectorAll('#ContactContainer')获取父容器,然后获取该元素的子元素,遍历子元素和forEach元素,如果Id等于你想要的,然后将其推送到数组或随心所欲。
  • 这可能会有所帮助:stackoverflow.com/questions/12155833/…

标签: javascript ecmascript-6


【解决方案1】:

您可以使用如下所示的通配符选择器来匹配部分属性标签,包括 id。

document.querySelector('[id*="MobileAreaCode"]');

如果您希望返回多个元素,请使用 querySelectorAll。

document.querySelectorAll('[id*="Mobile"]');

【讨论】:

  • 对不起,如果我遗漏了什么,但这适用于您提出的方式,但是如果元素包含字符串,例如 Home 或 Mobile,我如何找到它们。也许我理解不正确?
  • 在 id 属性中包含一个字符串?如果您正在寻找在 ID 属性(或任何其他属性)中包含部分字符串的多个元素,我更新了我的答案以显示如何。
  • 是的......所以有了这个txtCustomerHomeAreaCode,我想找到id包含Home等的元素......
  • 成功了,谢谢。我现在唯一的问题是这些元素位于 div 中,其 id 中包含相同的文本,所以现在我只需要找出如何获取输入。感谢您走上正确的道路
  • 刚刚想通了
猜你喜欢
  • 1970-01-01
  • 2011-01-05
  • 2021-03-02
  • 1970-01-01
  • 1970-01-01
  • 2012-04-27
  • 2016-03-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多