Javascript 如何允许表单元素具有多个类,并为错误消息连接/切片

Javascript 如何允许表单元素具有多个类,并为错误消息连接/切片,javascript,concatenation,elements,Javascript,Concatenation,Elements,我试图通过允许表单元素的标签来修改此代码 有不止一门课。我知道我必须使用连接来添加错误 类,并通过切掉最后一个空格后的文本来删除错误类 在className值中,但是我从哪里开始,我应该只修改跨度吗 function addErrorMessage(id, msg) { 'use strict'; // Get the form element reference: var elem = document.getElementById(id); //

我试图通过允许表单元素的标签来修改此代码 有不止一门课。我知道我必须使用连接来添加错误 类,并通过切掉最后一个空格后的文本来删除错误类 在className值中,但是我从哪里开始,我应该只修改跨度吗

    function addErrorMessage(id, msg) {
    'use strict';

    // Get the form element reference:
    var elem = document.getElementById(id);

    // Define the new span's ID value:
    var newId = id + 'Error';

    // Check for the existence of the span:
    var span = document.getElementById(newId);
    if (span) {
        span.firstChild.value = msg; // Update
    } else { // Create new.

        // Create the span:
        span = document.createElement('span');
        span.id = newId;
        span.className = 'error'
        span.appendChild(document.createTextNode(msg));

        // Add the span to the parent:
        elem.parentNode.appendChild(span);
        elem.previousSibling.className = 'error';

    } // End of main IF-ELSE.

} // End of addErrorMessage() function.

// This function removes the error message.
// It takes one argument: the form element ID.
function removeErrorMessage(id) {
    'use strict';

    // Get a reference to the span:
    var span = document.getElementById(id + 'Error');
    if (span) {

        // Remove the class from the label:
        span.previousSibling.previousSibling.className = null;

        // Remove the span:
        span.parentNode.removeChild(span);

    } // End of IF.

} // End of removeErrorMessage() function.

为什么不使用jQuery,这样就可以简单地使用addClass和removeClass

你还可以从hasClass之类的东西中获益,还有其他东西。。。

我没有在课堂上学习JQuery,所以我只能使用Javascript和HTMLI,我将在下午2点的会议后创建一个JSFIDLE。我认为最干净的方法可能是在空格字符上拆分类名,而不是依赖于它的序号位置,实际找到错误类并将其删除。