0
    window.onload = function(){
        var inputElement = document.getElementsByTagName('input');
        console.log(inputElement);
        console.log(inputElement.hasAttribute('placeholder'));
        if(inputElement.hasAttribute('placeholder')){
            console.log('true');
        }
    }; 

I keep getting a an TypeError on window.onload. Could someone point whats wrong with this, i am trying to to check if an input element has a placeholder attribute

Huangism
  • 16,278
  • 7
  • 48
  • 74
Raj
  • 107
  • 1
  • 3
  • 11
  • Look closer: it's getElement**s**ByTagName - plural. – georg Feb 09 '15 at 20:46
  • As in you have an *array* of elements, not the element itself. You need to loop through and check each one. – Spencer Wieczorek Feb 09 '15 at 20:47
  • Basically a duplicate of [Why getElementsByClassName does not work for me? What does it return?](http://stackoverflow.com/questions/10693845/why-getelementsbyclassname-does-not-work-for-me-what-does-it-return) (but this is for `getElementsByTagName` instead of `...ClassName`) – apsillers Feb 09 '15 at 20:52

2 Answers2

0
document.getElementsByTagName

returns an array or nodelist or whatever so you need to access its elements. What you're trying to do is run hasAttribute on the list, which apparently doesn't have such a function.

What you want is

var inputElement = document.getElementsByTagName('input')[0];

also if there are no input elements this will throw an error that there is no 0 index or something

php_nub_qq
  • 15,199
  • 21
  • 74
  • 144
0

If you really need to collect all of the inputs and look for placeholders, loop through the inputs that you've collected in inputElement and check each one.

I'd suggest something like this (though, I'd also recommend something in the log to indicate which inputs test positive for a placeholder ;) ):

window.onload = function() {
    var inputElements = document.getElementsByTagName('input');

    for (i = 0; i < inputElements.length; i++) {
        if (inputElements[i].hasAttribute('placeholder')) {
            console.log('true');
        }
    }
};

If you need to access a specific one, then you are going to have to figure out a way to identify the input uniquely (e.g., with an id attribute). Then you could use the approach that you are trying:

window.onload = function() {
    var inputElement = document.getElementById('some_id_value');

    if (inputElement.hasAttribute('placeholder')) {
        console.log('true');
    }
    else {
        console.log('false');
    }
};
talemyn
  • 7,822
  • 4
  • 31
  • 52