如何在 Google 自定义搜索输入元素之前插入标签元素?
How can I insert a label element before a Google Custom Search input element?
我正在使用 insertBefore() 尝试将 "label" 元素放置在 Google 自定义搜索输入元素之前以用作占位符文本,但使用我当前的代码时出现错误: "Cannot read property 'insertBefore' of undefined"。这是我的代码:
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>
尝试替换此行
document.searchParent.insertBefore(label, el);
有了这个:
document.insertBefore(label, searchParent);
解决方案是在使用 insertBefore() 时使用父元素而不是文档。
searchParent.insertBefore(label, el);
我正在使用 insertBefore() 尝试将 "label" 元素放置在 Google 自定义搜索输入元素之前以用作占位符文本,但使用我当前的代码时出现错误: "Cannot read property 'insertBefore' of undefined"。这是我的代码:
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>
尝试替换此行
document.searchParent.insertBefore(label, el);
有了这个:
document.insertBefore(label, searchParent);
解决方案是在使用 insertBefore() 时使用父元素而不是文档。
searchParent.insertBefore(label, el);