Reputation: 35720
I'd like to get all <input />
elements with the placeholder
property set, how could I do this without jquery? it should support IE6+, and other popular browsers.
Upvotes: 0
Views: 129
Reputation: 177861
Assuming all the fields have an ID
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
Upvotes: 1
Reputation: 147383
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.
Upvotes: 1
Reputation: 150030
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]);
}
Upvotes: 0
Reputation: 15579
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.
Upvotes: 0