Tobias H.
Tobias H.

Reputation: 505

Only execute code if element exists, but with no duplicate if statement in Javascript

I was wondering if you could make this:

if(document.getElementsByClassName("whatever")[0]) {
    document.getElementsByClassName("whatever")[0].style.display = "none";
}

(It checkes if the element exists, and then only executes the code if it is true)

But without the if statement, because it doesn't look like a good practice to duplicate the document.getElementsByClassName("whatever")[0], and it makes it more annoying when having to do a lot of bug testing with the document.getElementsByClassName.

Upvotes: 1

Views: 990

Answers (4)

not2savvy
not2savvy

Reputation: 4271

In my personal opinion, this is the simplest and still most elegant way to avoid the duplicate code, but also avoid extra code lines, so to keep it well readable:

if(elem = document.getElementsByClassName("whatever")[0]) {
    elem.style.display = "none";
}

Your editor might give you a warning about an assignment in a conditional expression. This seems totally okay to me, but you can avoid it by extra parens around the assignment. However, I think this reduces readability and should therefore better not be done.

Upvotes: 2

Nina Scholz
Nina Scholz

Reputation: 386736

You could destructure the element and assign only if element is truthy.

const [element] = document.getElementsByClassName("whatever");

if (element) element.style.display = "none";
<div class="whatever">1</div>
<div class="whatever">2</div>
<div class="whatever">3</div>

Upvotes: 0

Dan Cantir
Dan Cantir

Reputation: 2955

If you need to only hide the first element with a specific className, you can define a method like this:

function hideIfExists(className){
    var elements = document.getElementsByClassName(className);
    if(elements.length  > 0){
      elements[0].style.display = 'none';
    }
   
}

Then use it like this:

hideIfExists('hello')
hideIfExists('someOtherClass')
...

If you need it to hide all elements, your method might look like this

function hideIfExists(className){
    var elements = document.getElementsByClassName(className);
    for (let item of elements) {
      item.style.display = 'none';
    }
}

Upvotes: 1

Dave
Dave

Reputation: 29141

Simply set it to a variable, check if anything was found, and use that variable to modify it's display:

let whatever = document.getElementsByClassName("whatever");
if(whatever.length  > 0) {
    whatever[0].style.display = "none";
}

Upvotes: 1

Related Questions