How to get all elements with a given property?
I'd like to get all <input />
element开发者_如何学JAVAs with the placeholder
property set, how could I do this without jquery? it should support IE6+, and other popular browsers.
Assuming all the fields have an ID
DEMO
var fieldsWithPlaceholder = [];
var inputs = document.getElementsByTagName("input");
for (var i=0, n=inputs.length;i<n;i++) {
if (inputs[i].getAttribute("placeholder") !=null) {
fieldsWithPlaceholder.push(inputs[i].id);
}
}
alert(fieldsWithPlaceholder);
Update: you can as posted elsewhere test for null, undefined or blank in one go:
if (inputs[i].getAttribute("placeholder")) { // there is something there
Use getElementsByTagName, filter for those with a placeholder property value that isn't undefined.
Incidentally, there is a big difference between attributes and properties, which are you really after? If you are setting an attribute called placeholder in the HTML, then you should use getAttribute. However, if you are setting the property of a DOM element (which is what I presumed from your post) then you should use the property directly. Hopefully you aren't mixing the two.
In some browsers, attributes and properties are kept synchronised but in others they aren't. For example, Firefox will not create element properties for non–standard attributes (i.e. those that aren't specified in the related markup standard), nor will it create or modify standard attributes based on property changes in versions that aren't consistent with HTML5.
get all the elements of type input first
document.getElementsByTagName("input")
loop over the above list and then use the
getAttribute on each of the element as follows getAttribute("placeholder")
if it is not null or undefined then the input has it set.
Try something like this:
var myEls = [],
allEls = document.getElementsByTagName('input');
for (var i=0; i < allEls.length; i++) {
if (allEls[i].placeholder)
myEls.push(allEls[i]);
}
精彩评论