Reputation: 2107
My question is very similar to this one, but the difference is that I want to select an element by ID, then I want to select all elements that contain classes that starts with a a class name prefix
I tried
var x = $('#divID [class^="col-"]');
but that doesn't work
Upvotes: 0
Views: 114
Reputation: 414
This is the best answer to your question and i have checked this code personally.
$(document).ready(function(){
$("#divi_d [class^='col']").css("background-color", "yellow");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="divi_d">
<input name="nationality" type="text" value="Chinese">
<input name="nation" type="text" value="English">
<input class="col-lg-2" name="country" type="text" value="Germany">
<input name="anothernation" type="text" value="Norwegian">
</div>
<script>
$(document).ready(function(){
$("#divi_d [class^='col']").css("background-color", "yellow");});
</script>
please do not forget to include Jquery in the beginning.
let me know if you have any confusion.
Reference website www.webnius.com
Upvotes: 0
Reputation: 1074305
What you've shown does work, if the class appears at the beginning of the class
attribute. If it doesn't, you'll need to filter yourself:
var x = $("#divID *").filter(function() {
return this.className.split(" ").some(s => s.startsWith("col-"));
});
...which isn't ideal, but unless you're doing it hundreds of times a second, it's not a problem.
var x = $("#divID *").filter(function() {
return this.className.split(" ").some(s => s.startsWith("col-"));
});
x.css("color", "green");
<div id="divID">
<div class="foo col-xs-2">foo col-xs-2</div>
<div class="foo">foo</div>
<div class="foo col-xs-4 bar">foo col-xs-4 bar</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Instead, though, give your elements a common class in addition to the col-
class, so you can select on that.
Upvotes: 1