2014-10-31 110 views
1

選擇輸入我使用:不具有價值屬性與querySelector

document.querySelectorAll('input[value=""]') 

但它不選擇不具有屬性value輸入。
如何選擇所有沒有值''且沒有屬性值的輸入?

我想這樣做沒有jQuery和沒有任何額外的功能,這可能只有使用querySelectorAll

+0

這是一個有點混亂。你想選擇那些有價值的投入,或者那些沒有價值的投入? – LcSalazar 2014-10-31 19:38:54

回答

4

嘗試

document.querySelectorAll('input:not([value])')

這將返回所有input沒有了value屬性。

+0

這也是我的第一個想法,只導致:'未捕獲的SyntaxError:未能在'Document'上執行'querySelectorAll':'input:not(「[value]」)'不是有效的選擇器。「我* *引用了傳遞給':not()''的'[[value]「'選擇器)。 – 2014-10-31 19:39:20

+0

是的,不應該引用它。 – jsfrocha 2014-10-31 19:39:49

+1

那麼:[生活和學習](http://jsfiddle.net/davidThomas/dzrbvto9/),我想。 +1 – 2014-10-31 19:41:55

2

您可以使用此:

document.querySelectorAll('input:not([value]):not([value=""])'); 

get all inputs that doesn't have attribute "value" and the attribute "value" is not blank

var test = document.querySelectorAll('input:not([value]):not([value=""])'); 
 
for (var i = 0; i < test.length; ++i) { 
 
    test[i].style.borderColor = "red"; 
 
}
<input type="text" /> 
 
<input type="text" value="2" /> 
 
<input type="text" /> 
 
<input type="text" value="" /> 
 
<input type="text" />

+0

獲取所有* text *''元素(未指定限制),其'value'屬性設置爲空字符串,* not *''元素*沒有'value'屬性*(這是而不是問題的要求)。 – 2014-10-31 19:43:01

+0

hmm檢查更新答案@DavidThomas。 Thx反饋 – 2014-10-31 19:44:18