0

我知道我们可以使用 nodeName 获取节点名称,但是是否也可以使用 jquery 设置 nodeName ?基本上我想将节点名称的大小写从大写变为小写。

非常感谢

4

2 回答 2

3

我相信为了正确执行此操作,您需要按照此处所述替换该标签: jQuery:如何更改标签名称?

不幸的是,这将需要您替换整个元素而不仅仅是标签名称,因此如果您想替换标签名称,您需要找到一种方法来保留标签的属性以及其中的代码。

幸运的是,我有额外的几分钟,所以我创建了一个函数来做到这一点:

function change_tag_name(selector,tagname){
    var old_elm = $(selector);
    //Create a jquery element based on selector
    var original_elements = old_elm.get();
    //Get the array of original dom objects
    //Note: We get the original dom objects because jQuery objects do not provide access to the attributes array
    for(var i=0; i< original_elements.length; i+=1){
        var original_element = original_elements[i];
        //Create reference to original element in dom
        var new_elm = $(document.createElement(tagname));
        //Create new element with desired tagname
        new_elm.html($(original_element).html());
        //Add original element's inner elements to new element

        var original_attributes = original_element.attributes;
        //Create an array of the original element's attributes;
        var attributes = new Object();
        //Create a new generic object that will hold the attributes for the new element

        for(var j=0; j<original_attributes.length; j+=1){
            var attribute = original_attributes[j];
            var name = attribute.nodeName;
            //Note: The attributes "nodeName","localName",and "name" appear to have the same value, so I just chose one. It's entirely possible that these could have different values in different contexts...
            //var name = attribute.localName;
            //var name = attribute.name;
            var value = attribute.nodeValue;
            //Note: The attributes "nodeValue","textContext",and "value" appear to have the same value, so I just chose one. It's entirely possible that these could have different values in different contexts...
            //var value = attribute.textContext;
            //var value = attribute.value;
            attributes[name]=value;
        }
        //Populate attributes object
        new_elm.attr(attributes);
        //Assign attributes from old element to new element        
        $(original_element).replaceWith(new_elm);
        //Replace old_element with new element 
    }
}

另外,我认为没有办法保证属性按原始顺序排列。

于 2012-11-29T00:32:00.683 回答
0

您无法更改节点名称,但您可以创建一个具有不同名称的新节点,复制属性,然后将一个替换为另一个。

jQuery 使区分属性和属性变得困难,您可以使用 IE 专有的 outerHTML 属性(在其他一些浏览器中支持)和字符串操作,但这通常不适用于 Web。

如果有很多这样的节点,则全局替换 "

于 2012-11-28T23:35:37.710 回答