I am using insertBefore() to try to place a "label" element before a Google Custom Search input element to serve as placeholder text, but with my current code I am getting the error: "Cannot read property 'insertBefore' of undefined". Here is my code:
window.onload = function() {
var el = document.getElementById('gsc-i-id1');
el.setAttribute('placeholder', 'Enter your search term...');
el.style.background = '';
el.style.textIndent = '0';
el.addEventListener('blur', function(e) {
e.target.style.backgroundImage = 'none';
e.target.style.textIndent = '0';
}, false );
<!-- create absolutly positioned label as placeholder text for search -->
var searchParent = el.parentNode;
var label = document.createElement('label');
var labelText = document.createTextNode('Enter your search term...');
label.appendChild(labelText);
label.className += 'search-label-placeholder';
console.log(searchParent);
console.log(label);
console.log(el);
document.searchParent.insertBefore(label, el);
<!-- this doesn't work for adding a placeholder -->
var searchIcon = document.getElementById('search-icon');
searchIcon.addEventListener('click', function(e) {
e.preventDefault();
el.focus( function() {
el.setAttribute('placeholder', 'Enter your search term...');
});
}, false );
};
</script>
The solution was to use the parent element instead of the document when using insertBefore().
searchParent.insertBefore(label, el);