Javascript if(document.getElementById('something')!=null) 是否与 if(document.getElementById('something')) 相同?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3247251/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is if(document.getElementById('something')!=null) identical to if(document.getElementById('something'))?
提问by Malik Daud Ahmad Khokhar
When I want to check if an element exists in a page. Are these two checks the same? Is there a better more compact way to check the existence?
当我想检查页面中是否存在元素时。这两个检查一样吗?有没有更好更紧凑的方法来检查存在?
What if I want to check if the value == ''. Can this be included in this check as well?
如果我想检查value == ''. 这也可以包含在此检查中吗?
回答by Pointy
A reference to an element will never look "falsy", so leaving off the explicit null check is safe.
对元素的引用永远不会看起来“虚假”,因此省略显式空检查是安全的。
Javascript will treat references to some values in a boolean context as false: undefined, null, numeric zero and NaN, and empty strings. But what getElementByIdreturns will either be an element reference, or null. Thus if the element is in the DOM, the return value will be an object reference, and all object references are truein an if ()test. If the element is notin the DOM, the return value would be null, and nullis always falsein an if ()test.
Javascript 会将布尔上下文中对某些值的引用视为false:未定义、空、数字零和NaN以及空字符串。但是getElementById返回的要么是元素引用,要么是 null。因此,如果元素在 DOM 中,则返回值将是一个对象引用,并且所有对象引用都true在if ()测试中。如果元素不在DOM 中,则返回值将是null,并且null始终false处于if ()测试中。
It's harmless to include the comparison, but personally I prefer to keep out bits of code that don't do anything because I figure every time my finger hits the keyboard I might be introducing a bug :)
包含比较是无害的,但我个人更喜欢保留一些不做任何事情的代码,因为我认为每次我的手指敲击键盘时,我可能会引入一个错误:)
Note that those using jQuery should notdo this:
请注意,那些使用 jQuery 的人不应该这样做:
if ($('#something')) { /* ... */ }
because the jQuery function will always return something "truthy" — even if no element is found, jQuery returns an object reference. Instead:
因为 jQuery 函数总是会返回一些“真实”的东西——即使没有找到元素,jQuery 也会返回一个对象引用。反而:
if ($('#something').length) { /* ... */ }
edit— as to checking the valueof an element, no, you can't do that at the same time as you're checking for the existence of the element itself directly with DOM methods. Again, most frameworks make that relatively simple and clean, as others have noted in their answers.
编辑— 至于检查元素的值,不,您不能在直接使用 DOM 方法检查元素本身是否存在的同时这样做。同样,正如其他人在他们的回答中指出的那样,大多数框架都使这相对简单和干净。
回答by Andir
It's better (but wordier) to use:
使用更好(但更冗长):
var element = document.getElementById('something');
if (element != null && element.value == '') {
}
Please note, the first version of my answer was wrong:
请注意,我的答案的第一个版本是错误的:
var element = document.getElementById('something');
if (typeof element !== "undefined" && element.value == '') {
}
because getElementById()always return an object (null object if not found) and checking for"undefined"would never return a false, as typeof null !== "undefined"is still true.
因为getElementById()总是返回一个对象(如果未找到则为空对象)并且检查"undefined"永远不会返回 a false,因为typeof null !== "undefined"仍然true。
回答by Gawran
Just do it like this:
只需这样做:
if(!document.getElementById("someId") { /Some code. Note the NOT (!) in the expresion/ };
if(!document.getElementById("someId") { /一些代码。注意表达式中的 NOT (!)/ };
If element with id "someId" does not exist expresion will return TRUE (NOT FALSE === TRUE) or !false === true;
如果 id 为 "someId" 的元素不存在,表达式将返回 TRUE (NOT FALSE === TRUE) 或 !false === true;
try this code:
试试这个代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="format-detection" content="telephone-no">
<meta name="viewport" content="user-scalable=no, initial-scale=1, minimum-scale=1, maximum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi">
<title>Test</title>
</head>
<body>
<script>
var createPerson = function (name) {
var person;
if (!document.getElementById(name)) {
alert("Element does not exist. Let's create it.");
person = document.createElement("div");
//add argument name as the ID of the element
person.id = name;
//append element to the body of the document
document.body.appendChild(person);
} else {
alert("Element exists. Lets get it by ID!");
person = document.getElementById(name);
}
person.innerHTML = "HI THERE!";
};
//run the function.
createPerson("someid");
</script>
</body>
</html>
Try this in your browser and it should alert "Element does not exist. Let's create it."
在您的浏览器中尝试此操作,它应该警告“元素不存在。让我们创建它。”
Now add
现在添加
<div id="someid"></div>
to the body of the page and try again. Voila! :)
到页面正文,然后重试。瞧!:)
回答by Robusto
document.getElementById('something') can be 'undefined'. Usually (thought not always) it's sufficient to do tests like if (document.getElementById('something')).
document.getElementById('something') 可以是 'undefined'。通常(并非总是如此)进行诸如if (document.getElementById('something')).
回答by Fosco
Yeah. Try this.. lazy evaluation should prohibit the second part of the condition from evaluating when the first part is false/null:
是的。试试这个..懒惰评估应该禁止条件的第二部分在第一部分为假/空时进行评估:
var someval = document.getElementById('something')
if (someval && someval.value <> '') {
回答by NimChimpsky
jquerywill provide you with this and more ...
jquery将为您提供这个和更多...
if($("#something").val()){ //do stuff}
It took me a couple of days to pick it up, but it provides you with you with so much more functionality. An example below.
我花了几天时间才学会它,但它为您提供了更多功能。下面举个例子。
jQuery(document).ready(function() {
/* finds closest element with class divright/left and
makes all checkboxs inside that div class the same as selectAll...
*/
$("#selectAll").click(function() {
$(this).closest('.divright').find(':checkbox').attr('checked', this.checked);
});
});
回答by Pedro Pereira
Cleanest version specially good if you just want to get the .valuefrom the element.
如果您只想.value从元素中获取 ,那么最干净的版本特别好。
document.getElementById('elementsid') ? function_if_exists(); function_if_doesnt_exists();

