如何检查输入元素是否被隐藏?

时间:2011-08-06 10:37:07

标签: jquery

如何检查输入元素是否被隐藏?

4 个答案:

答案 0 :(得分:45)

隐藏为type="hidden"

$("#myInputElement").attr('type') == 'hidden'

隐藏为display: none

$("#myInputElement").is(":hidden")

答案 1 :(得分:15)

nickf是正确的,但这会对按样式(style="display:none;")或type属性(type="hidden")隐藏的输入产生相同的影响。
请考虑以下html:

<input id="first" type="hidden" />
<input id="second" type="text" style="display:none;"/>

以上两个输入都有:hidden伪类,但只有一个具有hidden类型。假设这是您正在寻找的(因为输入是唯一可以具有隐藏类型的元素,并且您想要检查输入元素是否被隐藏,而不仅仅是任何其他元素),右边回答你的问题是检查元素的类型属性:

document.getElementById('first').getAttribute('type') == 'hidden';// true
// although this input is also hidden, it wouldn't pass the check
document.getElementById('second').getAttribute('type') == 'hidden';// false

当然还有jquery方式:

$('#first').attr('type') == 'hidden';// true
$('#second').attr('type') == 'hidden';// false

如果你只对普通的可见性属性感兴趣,那么jquery伪类可以解决这个问题:

$('#first').is(':hidden');
// or another way
$('#first:hidden').length != 0;

答案 2 :(得分:0)

Element接口的getAttribute()方法返回元素上指定属性的值。如果给定属性不存在,则返回的值将为null""(空字符串);

对于隐藏的元素,您可以检查元素的type属性。

$('#myElement').getAttribute('type')=='hidden'

答案 3 :(得分:0)

HTMLElement.hidden如果拥有hidden属性,则应返回true。

document.querySelector('h1').hidden === true

我希望这会有所帮助。

相关问题