jeudi 28 mai 2015

JavaScript - If statement always returning true

I have some JavaScript that I want to search for a class name in the HTML, and then detect the height of a couple elements within that div, add them together, and display the total height in an alert. The following code appears to be running perfectly, but I noticed that the code will run regardless of what the class name is, even if that class doesn't exist within the HTML. How can I rewrite the if statement so it only runs the code once it comes across a div with the specified class name? I don't want it to detect the height of the wrong h1 and p elements. Thanks for any help.

HTML:

<div class="testing">
    <h1>Understanding Scope</h1>
    <p>By understanding code's <em>scope</em>, we know when that code affects only one part of our code, or the entire codebase.  If we create things that are <em>global</em> in scope, we are giving any code the supreme power to control our code.   So we want to protect our code by being very careful when creating things that are global in scope. This is especially important if you plan on using JavaScript libraries like jQuery.</p>
</div>
<h1>Local Scope</h1>
<p>JavaScript uses <em>function scope</em>, meaning every time we create a new function the scope changes.  Any code inside that function is <em>local</em> to that function. Code that is local in scope is not accessible to outside code.</p>

JavaScript:

function testing(){
        if (document.getElementsByClassName('testing')){
            var headerHeight = document.getElementsByTagName('h1')[0].offsetHeight;
            var textHeight = document.getElementsByTagName('p')[0].offsetHeight;
            var totalHeight = headerHeight + textHeight;


            alert(totalHeight);

        }
    }
testing();

Aucun commentaire:

Enregistrer un commentaire