【问题标题】:Is possible to get an unique id of HTML tag without using the id field?是否可以在不使用 id 字段的情况下获取 HTML 标签的唯一 id?
【发布时间】:2018-04-23 02:20:02
【问题描述】:

我试图了解是否有机会在不使用标签上的 id 属性的情况下从 HTML 标签/节点获取唯一 ID,我的情况是这样的:

<!-- div #1 -->
<div style="width:200px; height:200px;"><script src="myScript.js"></script></div>
<!-- div #2-->
<div style="width:200px; height:200px;"><script src="myScript.js"></script></div>

对于 myScript.js,我想以独特的方式识别两个 div,例如:

//pseudo code of myScript.js
// let ids = [];
for(element in dom){
    if(dom[element] is one_of_the_div_I_was_looking_for){
        ids.push(dom[element].uniqueDivIdentifier);
    }
}

编辑:

更多案例信息:

  1. 我无法在 div 中添加任何类型的属性。
  2. 我不能使用 jQuery
  3. 我不会是创建 HTML 结构的人
  4. n°的div是随机的,甚至是样式属性中的位置和尺寸,所以我也可以有&lt;div style="width:300px; height:250px;"&gt;&lt;script src="myScript.js"&gt;&lt;/script&gt;&lt;/div&gt;

提前致谢

【问题讨论】:

  • 考虑使用 jQuery,如果你可以使用库,以减轻编写超出需要的 js 的痛苦。 api.jquery.com/find
  • @HarishST 不,在这种情况下我不走运 :)
  • 这是一个类似的问题。那里的对话会给你一些想法。 stackoverflow.com/questions/2367778/…
  • 正如我在回答中所写的那样,底线,走哪条路对于做什么以及应该如何使用/访问这些元素非常重要,而这些都没有在您的问题(这也可能是您投反对票的原因之一)。

标签: javascript html dom


【解决方案1】:

如果您知道它们出现的顺序,那么在诸如querySelectorAll 返回的列表中,第一个将在第二个之前。示例:

var list = document.querySelectorAll("#container div");
var n = 0;
setInterval(function() {
  list[n].classList.remove("highlight");
  n = n == 0 ? 1 : 0;
  list[n].classList.add("highlight");
}, 500);
.highlight {
  color: blue;
}
<div id="container">
  <!-- div #1 -->
  <div style="width:200px; height:200px;">testing 1 2 3</div>
  <!-- div #2-->
  <div style="width:200px; height:200px;">testing 1 2 3</div>
</div>

【讨论】:

    【解决方案2】:

    你可以使用:

    • id 选择器
    • 类选择器
    • 像 jQuery 这样的库..

    但是如果你不想修改html,你甚至可以通过样式属性来选择,(不是最好的方法...)

    var elms = document.querySelectorAll('*[style="width:200px; height:200px;"]');
    elms[0].style.background='red';
    7
    <!-- div #1 -->
      <div style="width:200px; height:200px;">testing 1 2 3</div>
      <!-- div #2-->
      <div style="width:200px; height:200px;">testing 1 2 3</div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-08
      • 2013-04-18
      • 2020-03-03
      • 2019-08-01
      • 1970-01-01
      • 2012-09-12
      • 2021-06-10
      • 1970-01-01
      相关资源
      最近更新 更多