我正在尝试使用类名 Plain Javascript 获取第一个子元素。
我正在尝试编写自己的表单验证并尝试附加错误消息并将其删除。如果错误消息已经存在,则不要追加。
如果您帮助我完成第一部分,为 child 提供类(class)名称,那就太好了。
function display_error(selector, message) {
selector.insertAdjacentHTML('afterend', "<h1 class='js-error' >" + message + "</h1>");
}
function validateForm() {
// Validate Name Field
// Check if name has les than 3
var elem = document.getElementById("name")
if (elem.value.length < 3) {
display_error(elem, "Less than 3")
return false;
} else {
// here is the error
error_label = elem.querySelector('.js-error');
error_label.textContent = "more than 3"
}
}
这是一个 fiddle https://jsfiddle.net/efh941cc/3/
最佳答案
关于的美丽之处 document.querySelector()
的一个优点是您可以使用 CSS 选择器,而不是通常笨重的 DOM API。
CSS 提供了一个非常简单的选择器,称为 first-child
这正是您所需要的。
// Find the first element that uses the .test class that is a child of another element.
var firstTest = document.querySelector(".test:first-child");
// Now that you've scanned and found the element and stored a reference to it
// in a variable, you can access any aspect of the element.
console.log(firstTest.textContent);
firstTest.innerHTML = "<span>Now, I have completely different content than before!</span>";
// Now, we can get a reference to other elements that are relative to the last
// one we found.
var firstTestError = document.querySelector(".test:first-child + .error");
firstTestError.style.backgroundColor = "aqua";
firstTestError.innerHTML = "<span>Required</span>";
<div>
<span class="test">one</span><span class="error"></span>
<div class="test">two</div>
<div class="test">three</div>
</div>
关于javascript - 获取具有类名的第一个下一个元素 Plain Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43826386/