I have some DIVs wi开发者_StackOverflowth ID "div1", "div2" ... "divx". I want to perform an operation on them. Is there any way to get the element ID .contains "div". Any other idea?
You can use the starts with selector
$("div[id^='div']")
The above will grab all divs that have an id
attribute that begins with the letters div
.
jsFiddle example that makes all divs with id div...
invisible.
Here's how to handle the trickier case if you want to match div
followed by a number but not div
followed by something else. So div1
would match, but divx
would not.
In this case we use filter() with a function. The function should return true for when we want a match and false for when we do not. match() and a regex is great for this (you can use [0-9]
to represent a digit in a regex or the simpler [\d]
):
$("div").filter(function() {
return $(this).attr("id").match(/^div[\d]+$/)
})
attr() returns the value of the specified attribute, in this case id
.
jsFiddle example that makes all div
followed by number disappear, but not div
followed by other things.
You could use this (I haven't tested it though):
jQuery("div[id^='div']")
This will get all div
elements that have an id
beginning with "div".
If you wanted all the div
elements that have an id
containing "div", then you could use this:
jQuery("div[id*='div']")
Using ID's like div1, div2, div3 is a bad practice. It's like naming your classes "black-bold-12px" and then assigning those styles to that class. It misses the point on semantics.
The right way for doing this would be using a class for all of them.
Elements can be of more than one class, using a space as separator:
<div class="something usethis">...</div>
<div class="usethis something_else">...</div>
<div class="usethis">...</div>
<div class="something anotherclass usethis" id="someId">...</div>
<script>
$(".usethis").html("New contents for all of them!");
</script>
精彩评论