0

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();

4 Answers 4

10

Even if your document query returns an empty array, it's still true

This is because [] is a "truthy" value.

if ([]) { console.log("always true"); }

Instead try

var elems = document.getElementsByClassName("foo");

if (elems.length > 0) {
  // ...
}

If you don't care to access the elems later, you can skip the intermediate variable

if (document.getElementsByClassName("foo").length > 0) // ...

Per your comment

var div = document.getElementsByClassName("testing");

if (div.length > 0) {
  div[0].getElementsByTagName("h1")[0] ...
  div[0].getElementsByTagName("p")[0] ...
}

This will find tags within the context of div instead of the global document context.

Sign up to request clarification or add additional context in comments.

2 Comments

This seems to just check whether or not that div exists and then proceeds to look for the height of the first h1 and p elements of the entire document. I want it to look for first h1 and p elements strictly from that div.
@Bryan, I've provided an edit to address your comment
4

Change

 if (document.getElementsByClassName('testing')){ //This will always be true

to

 if (document.getElementsByClassName('testing').length){//This depends on lenght , could be 0

1 Comment

This seems to just check whether or not that div exists and then proceeds to look for the height of the first h1 and p elements of the entire document. I want it to look for first h1 and p elements strictly from that div.
1

The thing here is, that you create with document.getElementsByClassName(something). So the element exists, but it is empty. Therefore it has a length 0.

var el = document.getElementsByClassName('testa');
console.log(el); // []

You can check with length:

if(document.getElementsByClassName('testing').length > 0)

1 Comment

This seems to just check whether or not that div exists and then proceeds to look for the height of the first h1 and p elements of the entire document. I want it to look for first h1 and p elements strictly from that div.
0

I think you want to use document.getElementById instead of document.getElementsByClassName.

I've seen getElementsById used in this way like so:

var elementExists = document.getElementById("targetID");

which wold be similar to what you want to do.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.