Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get HTML element using jQuery

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?

like image 308
John Donvan Avatar asked Aug 12 '10 02:08

John Donvan


People also ask

How HTML element are used in jQuery?

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.

How do I get the innerHTML value?

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.

How do I get DOM element?

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.


2 Answers

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.

like image 122
Peter Ajtai Avatar answered Oct 04 '22 06:10

Peter Ajtai


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']")
like image 29
Dumb Guy Avatar answered Oct 04 '22 06:10

Dumb Guy