hasClass function

I’m trying to find a specific class of an element using the hasClass function as shown on page 88 of Simply Javascript.

I’m not using the Core library as I want to understand how this works outside of a library environment.

Basically the way I set it up was to just send me an alert when the element is found.

I will attach my files for you to peruse and show me the error of my ways. :slight_smile:

It seems that your substitute function is buggy. By using a series of alerts I could track down the problem somewhat.

        for (var i = 0; i < elementArray.length; i++) {
//alert(i); // TROUBLESHOOTING - OK
//alert(target.className); // TROUBLESHOOTING - undefined
//alert(target); // TROUBLESHOOTING - h1
//alert(elementArray); // TROUBLESHOOTING - object HTMLCollection
//alert(elementArray[i].className); // TROUBLESHOOTING - OK
//            if (pattern.test(target.className)) {
            if (pattern.test(elementArray[i].className)) {
                alert("Found!");
                // return true;
            }
        }

Alert:
1 - shows the for loop is working
2 - there’s a problem with what you’re testing
3 - the variable “target” is being passed OK
4 - the for loop is iterating through a collection object
5 - className is a property of a collection object item

Hi rick yentzer, welcome to the forums,

All attached files are screened for viruses by Moderators before they’re approved.

The Questions forum is not one of the busiest forums, so you may nott get help right away. I am not familliar with the Simply Javascript book, but I’ll take a look and see what I can see and post back ASAP

thank you for your response. That is a great way to troubleshoot. I didn’t use my alerts as effectively as you. That will certainly prove to be beneficial in the future. Thanks again.

I’ll unzip the files in case anyone is afraid it’s malicious and combine the script into the html. But Please someone help me get past this.

Why is my “target” element not being found even though it has the class being requested? The script is at the bottom of the html just before the closing body tag.

I can’t think of anything else.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en-US" xml:lang="en-US">
<head>
  <title>Tag Name Locator</title>
  <meta http-equiv="content-type" content="text/html; charset=utf-8" />
  <link rel="stylesheet" type="text/css" href="base.css" />
</head>
<body>
<h1 class="bookSection">Document Access</h1>
  <p>To create the DOM for a document, each element in the HTML is represented by what&rsquo;s known as a node. A node&rsquo;s position in the DOM tree is determined by its parent and child nodes.</p>
  <h1 id="subSection" class="bookSection partTwo">Accessing the Nodes you want</h1>
  <p>Different ways to get to the nodes.</p>
  <h2>How to find elements based on class name</h2>
  <p id="linkMe">We can combine <a id="google" href="http://www.google.com">getElement(s)</a> to create a find by class name.</p>
  <h1 class="bookSection" >Navigating the DOM Tree</h1>
  <p>Otherwise known as walking the DOM.</p>
  <ul>
    <li><h2>Parent Node</h2>
        <p>Every element but the document node has a parent.</p>
    </li>
  </ul>

  <ul id="baldwins">
      <li>Alec</li>
      <li>Daniel</li>
      <li>William</li>
  </ul>

<script type="text/javascript">
    function hasClass(target, theClass) {
        
        // all elements array
        var elementArray = [];
        
        // test for document.all vs *
        if (document.all) {
            elementArray = document.all;
        } else {
            elementArray = document.getElementsByTagName("*");
        }

        // test pattern
        var pattern = new RegExp("(^| )" + theClass + "( |$)");
        
        // walk through the elementArray looking for the elements
        // that contain the specified class
        for (var i = 0; i < elementArray.length; i++) {
            if (pattern.test(target.className)) {
                alert("Found!");
                // return true;
            }
        }
        alert("Not Found");
        // return false;
        
    } // end function
    
    hasClass("h1", "bookSection");
</script>

</body>
</html>

anyone have any words of wisdom?

Hello rick,

I was playing around with your code and the bolded part is what I found that’s preventing your code from working:

<script type=“text/javascript”>

for (var i = 0; i < elementArray.length; i++)
{
if (pattern.test(target.className))
{
alert(“Found!”);
// return true;
}
}

</script>

If you replace target with elementArray[i], the code will run. I’m not an expert on javascript, but it seems that the element nobe being picked up inside the loop is not recognized as h1.

I added a bit more detail to rick’s code to show what is actually stored in the matched elementArray,

<script type=“text/javascript”>

for (var i = 0; i < elementArray.length; i++)
{
if (pattern.test(elementArray[i].className))
{
alert(“Found!” + " " +elementArray[i]);
// return true;
}
}

</script>

and the alert message shows: Found! [object HTMLHeadingElement]

I am not an expert on javascript. Can someone please explain

  1. why target.className cannot be used in this case?
  2. why h1 is recognized not just h1, but HTMLHeadingElement inside elementArray[i]?

Thank you :slight_smile: