We help IT Professionals succeed at work.

Test if h2 contains specific css class

hankknight
hankknight asked
on
Medium Priority
272 Views
Last Modified: 2012-05-06
I want to test if the div with an id of "result" contains an h2 tag with a class of "error"

This should trigger an alert:
<div id="result"><h2 class="error">There Was an Error</h2></div>

This should NOT trigger an alert:
<div id="result"><h2 class="success">Success!</h2></div>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Demo</title>
</head>
<body>
<h1>Management Area</h1>
<div id="result"><h2 class="error">There Was an Error</h2></div>
<p>Content Here</p>
<script type="text/javascript">
	var obj = document.getElementById('result');
	if (obj contains an h2 with a class of error) {
            alert('Error');
	}	
</script>
 
</body>
</html>

Open in new window

Comment
Watch Question

Hi, here's a quick javascript to help you out. You need to modify it according to your page
In your case you just need to add slightly more complicated logic depending on what you want
to do if you find that type of error css class.
Fetch the element using script like this:
var myvar1;
myvar1 = document.getElementsByTagName('h2')


then you need to check its class property like this:

if(myvar1.className=="error")
 {
 trigger alert
}
else
{
do something else
}


Not the solution you were looking for? Getting a personalized solution is easy.

Ask the Experts
Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

  • View three pieces of content (articles, solutions, posts, and videos)
  • Ask the experts questions (counted toward content limit)
  • Customize your dashboard and profile

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.