Given an HTML document containing some CSS property and the task is to check whether an element has a specific CSS style or not with the help of jQuery.
Approach 1: Use css() method to check an element contains certain CSS styles or not.
Example: This example uses css() method to check an element contains certain CSS style or not.
<!DOCTYPE HTML> < html > < head > < title > How to check an element has certain CSS style using jQuery ? </ title > < script src = </ script > </ head > < body style = "text-align:center;" > < h1 style = "color:green" > GeeksForGeeks </ h1 > < p id = "GFG_UP" style = "font-size: 15px; font-weight: bold;" > </ p > < button onclick = "GFG_Fun()" > click here </ button > < p id = "GFG_DOWN" style = "color:green; font-size: 20px; font-weight: bold;" > </ p > < script > var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); var n = 1/0; up.innerHTML = "Click on the button to check" + " if H1 has style, color = green."; function GFG_Fun() { if ($("#h1").css("color") == "rgb(0, 128, 0)") { down.innerHTML = "H1 has CSS style, color: green"; } else { down.innerHTML = "H1 has not CSS style, color: green"; } } </ script > </ body > </ html > |
Output:
- Before clicking on the button:
- After clicking on the button:
Approach 2: Use hasClass() method to check an element contains certain CSS styles or not.
Example: This example uses hasClass() method to check an element contains certain CSS style or not.
<!DOCTYPE HTML> < html > < head > < title > How to check an element has certain CSS style using jQuery ? </ title > < script src = </ script > </ head > < body style = "text-align:center;" > < h1 style = "color:green;" > GeeksForGeeks </ h1 > < p id = "GFG_UP" style = "font-size: 15px; font-weight: bold;" > </ p > < button onclick = "GFG_Fun()" > click here </ button > < p id = "GFG_DOWN" class = "color" style = "font-size: 20px; font-weight: bold;" > </ p > < script > var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); var n = 1/0; up.innerHTML = "Click on the button to check if" + " P[id = GFG_DOWN] has style, color =" + " green using class."; function GFG_Fun() { if ($("#GFG_DOWN").hasClass('color')) { down.innerHTML = "P[id = GFG_DOWN] has CSS style, color: green"; } else { down.innerHTML = "P[id = GFG_DOWN] has not CSS style, color: green"; } } </ script > </ body > </ html > |
Output:
- Before clicking on the button:
- After clicking on the button: