I am attempting to assign different values to the same variable in javascript based on whether an element exists in the DOM or not. So far I have
if(document.body.contains(document.getElementById('a'))){
var newVar = document.getElementById('a').innerHTML;
} else if(document.body.contains(document.getElementById('b'))){
var newVar = document.getElementById('b').innerHTML;
}
However, this only works if the checked variable 'a' exists. I am aware that this approach is perhaps a bit unconventional, and was wondering if there was a simple way to do it, or if it is impossible since it's the same variable declared.
If you just want to get the innerHTML
property of the first present element you can use a querySelector
, where the query consists of the searching queries of each of the elements separated by ,
Something like:
var dom = document.querySelector("#a, #b");
if (dom instanceof HTMLElement) console.log("Found :" + dom.innerHTML);
else console.log("Not found");
Examples:
var newVar = (document.querySelector("#a, #b") || {}).innerHTML;
console.log(newVar || "Not found");
<div id="a">Hello A</div>
<div id="b">Hello B</div>
var newVar = (document.querySelector("#a, #b") || {}).innerHTML;
console.log(newVar || "Not found");
<div id="a">Hello A</div>
var newVar = (document.querySelector("#a, #b") || {}).innerHTML;
console.log(newVar || "Not found");
<div id="b">Hello B</div>
var newVar = (document.querySelector("#a, #b") || {}).innerHTML;
console.log(newVar || "Not found");