Given an HTML document and the task is to select the elements with ID starts with certain characters using jQuery.
Approach: Use jQuery [attribute^=value] Selector to select the element with ID starts with certain characters.
Example 1: This example selects that element whose ID starts with ‘GFG’ and change their background color.
<!DOCTYPE HTML> < html > < head > < title > How to select ID starts with certain character in jQuery ? </ title > < style > #GFG_DIV { background: green; height: 100px; width: 200px; margin: 0 auto; color: white; } </ style > < script src = </ script > </ head > < body style = "text-align:center;" > < h1 style = "color:green;" > GeeksForGeeks </ h1 > < p id = "GFG_UP" style = "font-size: 19px; font-weight: bold;" > </ p > < div id = "GFG_DIV" > This is Div box. </ div > < br > < button onClick = "GFG_Fun()" > click here </ button > < p id = "GFG_DOWN" style = "color: green; font-size: 24px; font-weight: bold;" > </ p > < script > $('#GFG_UP').text("Click on button to change " + "background-color of element's " + "ID starts with 'GFG'"); function GFG_Fun() { $( "[id^='GFG']" ).css("background-color", "pink"); $('#GFG_DOWN').text("Div hides after 1 second."); } </ script > </ body > </ html > |
Output:
-
Before clicking the button:
-
After clicking the button:
Example 2: This example selects the elements whose ID starts with ‘GFG’ and set their background color.
<!DOCTYPE HTML> < html > < head > < title > How to select ID starts with certain character in jQuery ? </ title > < style > #GFG_DIV { background: green; height: 100px; width: 200px; margin: 0 auto; color: white; } </ style > < script src = </ script > </ head > < body style = "text-align:center;" > < h1 style = "color:green;" > GeeksForGeeks </ h1 > < p id = "GFG_UP" style = "font-size: 19px; font-weight: bold;" > </ p > < div id = "GFG_DIV" > This is Div box. </ div > < br > < button onClick = "GFG_Fun()" > click here </ button > < p id = "GFG_DOWN" style = "color: green; font-size: 24px; font-weight: bold;" > </ p > < script > $('#GFG_UP').text("Click on button to change " + "background-color of element's " + "ID starts with 'GFG'"); function GFG_Fun() { var value = "GFG"; $("[id^='" + value + "']" ).css("background-color", "pink"); $('#GFG_DOWN').text("Div hides after 1 second."); } </ script > </ body > </ html > |
Output:
-
Before clicking the button:
-
After clicking the button: