如何在DOM中找到具有z-index值的所有元素

时间:2019-01-22 14:30:22

标签: javascript jquery

我的代码中有一个表,其中包含很多行,每行都包含一些td,我想找到所有具有z-index值的td。

例如-

<table>
    <thead>
        <tr>
            <td>name</td>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td style="z-index: 10">jhon</td>
        </tr>
        <tr>
            <td>
                doy
            </td>
        </tr>
        <tr>
            <td style="z-index: 20">jam</td>
        </tr>
    </tbody>
</table>

有人可以帮我找到所有具有z-index值的td,而无需使用任何循环吗?

2 个答案:

答案 0 :(得分:1)

您可以找到所有.then(function() { return gapi.client.request({ path: `https://www.googleapis.com/calendar/v3/calendars/${CALENDAR_ID}/events?maxResults=11&orderBy=updated&timeMin=${moment().toISOString()}&timeMax=${moment() .endOf("day") .toISOString()}` }); }) ,然后过滤掉没有设置z-index的那些。我很确定没有比这更具体的级别了。

td
const test = [
  ...document.getElementsByTagName("td")
].filter(x => x.style.zIndex !== "")

test.forEach(x => x.style.color = "#"+((1<<24)*Math.random()|0).toString(16))

console.dir(test)

答案 1 :(得分:0)

所以这给了你相同的结果,但是使用了jQuery,这就是为什么我添加了一个

position:relative

For z-index to work correctly, every element that has a z-index property must also have any position set ( e.g.position:relative )

$(document).ready(function() {
  $("td").each(function() {

    // td Element
    const $this = $(this);

    // your logic condition 
    if ($this.css("z-index") !== "auto") {
      $this.css("color", "red");
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<table>
  <thead>
    <tr>
      <td>name</td>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td style=" position: relative; z-index: 10">jhon</td>
    </tr>
    <tr>
      <td>
        doy
      </td>
    </tr>
    <tr>
      <td style=" position: relative; z-index: 20">jam</td>
    </tr>
  </tbody>
</table>