通过它的最后两个字符来定位元素

时间:2013-09-25 21:07:12

标签: jquery element

我有以下HTML:

<div id="wrapper">
     <div id="a_12"></div>
     <div id="a_13"></div>
     <div id="a_14"></div>
     <div id="a_15"></div>
     <div id="a_16"></div>
     <div id="a_17"></div>
</div>

如何使用jQuery选择以15结尾的div?

2 个答案:

答案 0 :(得分:6)

使用attribute-ends-with选择器:

$('div[id$="15"]');

$('div[id$="15"]').css('color', '#f90');
div {
  border: 1px solid #000;
  width: 50%;
  margin: 0 auto 0.5em auto;
}
div[id]::before {
  content: attr(id);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wrapper">
  <div id="a_12"></div>
  <div id="a_13"></div>
  <div id="a_14"></div>
  <div id="a_15"></div>
  <div id="a_16"></div>
  <div id="a_17"></div>
</div>

JS Fiddle demo

或者,您可以使用filter()

$('div').filter(function(){
    return this.id.slice(-2) == '15';
});

$('div').filter(function() {
  return this.id.slice(-2) == '15';
}).css('color', '#f90');
div {
  border: 1px solid #000;
  width: 50%;
  margin: 0 auto 0.5em auto;
}
div[id]::before {
  content: attr(id);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wrapper">
  <div id="a_12"></div>
  <div id="a_13"></div>
  <div id="a_14"></div>
  <div id="a_15"></div>
  <div id="a_16"></div>
  <div id="a_17"></div>
</div>

JS Fiddle demo

或者,使用纯JavaScript:

document.querySelector('div[id$="15"]').style.color = '#f90';

document.querySelector('div[id$="15"]').style.color = '#f90';
div {
  border: 1px solid #000;
  width: 50%;
  margin: 0 auto 0.5em auto;
}
div[id]::before {
  content: attr(id);
}
<div id="wrapper">
  <div id="a_12"></div>
  <div id="a_13"></div>
  <div id="a_14"></div>
  <div id="a_15"></div>
  <div id="a_16"></div>
  <div id="a_17"></div>
</div>

JS Fiddle demo

甚至只用CSS:

div[id$="15"] {
  color: #f90;
}

div {
  border: 1px solid #000;
  width: 50%;
  margin: 0 auto 0.5em auto;
}
div[id]::before {
  content: attr(id);
}

div[id$="15"] {
  color: #f90;
}
<div id="wrapper">
  <div id="a_12"></div>
  <div id="a_13"></div>
  <div id="a_14"></div>
  <div id="a_15"></div>
  <div id="a_16"></div>
  <div id="a_17"></div>
</div>

JS Fiddle demo

参考文献:

答案 1 :(得分:2)

尝试在属性值上使用ends with selector

$('#wrapper').find('[id$="15"]'); //here find on the wrapper since you never know you may have some other element with id ends with 15 on your page.

当使用带选择器的结尾时,你必须小心,所以提供尽可能多的特异性来最终选择正确的。

<强> Fiddle