I have some DIVs with 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?
jQuery html() MethodThe html() method sets or returns the content (innerHTML) of the selected elements. When this method is used to return content, it returns the content of the FIRST matched element. When this method is used to set content, it overwrites the content of ALL matched elements.
Firstly, to get the innerHTML value of any tag, you either need that tag to have its 'id' property or 'name' property set. Then you can respectively use the 'document. getElementById(yourTagIdValue). innerHTML' or 'document.
The easiest way to access a single element in the DOM is by its unique ID. You can get an element by ID with the getElementById() method of the document object. In the Console, get the element and assign it to the demoId variable. const demoId = document.
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']")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With