Test if h2 contains specific css class

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

LVL 16
hankknightAsked:
Who is Participating?
 
techExtremeConnect With a Mentor Commented:
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
}


0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.