Reputation: 505
I have the following 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>
How can I select the div that ends with 15 using jQuery?
Upvotes: 2
Views: 69
Reputation: 253308
Use the attribute-ends-with selector:
$('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>
Or, you could use 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>
Or, with plain 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>
Or even with just 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>
References:
[attribute$="value"]
) selector.filter()
.Upvotes: 6
Reputation: 123739
Try using ends with selector on attribute value:
$('#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.
When using ends with selector, you must be careful, so provide as much specificity as possible to end up selecting the right one.
Upvotes: 2