Noah Faria
Noah Faria

Reputation: 21

Unable to properly detect if an element exists

var element = document.getElementsByClassName('btn btn-secondary btn-buy add-cart');

if(typeof(element) != 'undefined' && element != null){
  alert('Element Exists!');
}else{
  alert('Element does not exist')
}

Hey so I am trying to detect if an element exists or not on a page, and respectively execute a function according to if it exists or not.

I was testing and event when I replace the element to detect with random letters (to see if it gives the "Element does not exist" response, it still says that the element exists.

Any help is appreciated on what I can improve.

Thankyou

Upvotes: 2

Views: 100

Answers (3)

ObsoleteAwareProduce
ObsoleteAwareProduce

Reputation: 756

GetElementsByClassName returns an array (Edit: as @charlietfl pointed out below, it's technically a HTMLCollection, acting similar to an array, but not the same), which may or may not be empty, but will not be undefined or null. You should change it to:

var element = document.getElementsByClassName('btn btn-secondary btn-buy add-cart')[0];

The [0] picks the first element, which may or may not exist. It will be undefined if it is nonexistent.

Upvotes: 1

Karl L
Karl L

Reputation: 1725

getting the .length is enough, if it cant find any matching elements, then length will be 0 and it means false, otherwise any other positive number is true

let element = document.getElementsByClassName('btn btn-secondary btn-buy add-cart')

 let nonExistingEl = document.getElementsByClassName('someclass ')


element.length ? console.log('Element Exists!') : console.log('Element does not exist')

nonExistingEl.length ? console.log('Element Exists!') : console.log('Element does not exist')
<div class="btn btn-secondary btn-buy add-cart">

</div>

Upvotes: 0

Sascha A.
Sascha A.

Reputation: 4616

GetElementsByClassName returns an array of all elements to these classes, so it's enough to test it on the length .
GetElementByClassName returns the first occurence if an element exists.
Difference is only the s for the plural in the name.

var element = document.getElementsByClassName('btn btn-secondary btn-buy add-cart');

if (element.length) {
  console.log('Element Exists!');
}else{
  console.log('Element does not exist')
}

var element2 = document.getElementsByClassName('btn red');

if (element2.length) {
  console.log('Element Exists!');
}else{
  console.log('Element does not exist')
}
<button class='btn btn-secondary btn-buy add-cart'>Button</button>

Upvotes: 0

Related Questions