首页 > 解决方案 > dom元素可见性对javascript很重要吗

问题描述

我知道id对于当前的 dom 必须是唯一的,但是即使 2 个 dom 元素永远不会同时可见,这是否成立。

我有这种情况:

<div class="visible-lg visible-md">
  <div id="test"></div>
</div>
.
.
.
<div class="visible-sm visible-xs">
 <div id="test"></div>
</div>

<script>
  .
  .
  .
   document.getElementById("test").innerHTML = "this text";
</script>

无论我使用什么设备尺寸,只有第一个元素会得到更新。如何确保正确的元素得到更新?

标签: javascriptdomtwitter-bootstrap-3

解决方案


I know id has to be unique for the current dom, but does that hold even if the 2 dom elements will never be visible at the same time.

Yes. Visibility is irrelevant, ids must be unique. It's not a JavaScript thing, it's a DOM thing [the layer under HTML]:

An element can have an associated unique identifier (ID)

Note the term "unique."


推荐阅读