[英]return Element if exists using ternary operator by the shorten way as possible in JS
Is there any way to shorten the myFx()
function without repeating document.getElementById('myID')
?有什么方法可以缩短myFx()
function 而不重复document.getElementById('myID')
? I just want to return the Element if it exists, if it doesn't, return "false".我只想返回元素(如果存在),如果不存在,则返回“false”。
The function is working well that manner, but I would like to know if there is any way to shorten it a little more. function 以这种方式运行良好,但我想知道是否有任何方法可以将其缩短一点。
HTML: HTML:
<div id="myID">Hello World!</div>
JavaScript: JavaScript:
function myFx(){
return (document.getElementById('myID') === null) ? false : document.getElementById('myID');
}
myFx().innerHTML = "Goodbye Cruel World!";
Use Nullish coalescing operator (??) .使用Nullish 合并运算符 (??) 。
The nullish coalescing operator (??) is a logical operator that returns its right-hand side operand when its left-hand side operand is
null
orundefined
, and otherwise returns its left-hand side operand.空值合并运算符 (??) 是一个逻辑运算符,当其左侧操作数为null
或undefined
时返回其右侧操作数,否则返回其左侧操作数。
function myFx() { return document.getElementById('myID')?? false; } myFx().innerHTML = "Goodbye Cruel World;";
<div id="myID">Hello World!</div>
The answer of @c0m1t is correct, just be aware that this might not work in older browsers. @c0m1t 的答案是正确的,请注意这可能不适用于旧版浏览器。 I am not sure if it's still a real issue today, but anyway.. here is solution which should work even in ancient browsers.我不确定它今天是否仍然是一个真正的问题,但无论如何......这里的解决方案即使在古代浏览器中也应该适用。
function myFx(){
var element = document.getElementById('myID');
return element || false;
}
myFx().innerHTML = "Goodbye Cruel World!";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.