【问题标题】:How do you display the contents of tags such as tag names and attributes as strings?如何将标签的内容(如标签名称和属性)显示为字符串?
【发布时间】:2011-05-12 04:29:56
【问题描述】:

好的,所以我想做的是使用 DOM 自省递归地分析 DOM 的当前状态,并将其作为单个格式化字符串返回以显示在其他地方。 标准 DOM 函数或 JQuery 都足以满足我的目的。 到目前为止,我已经尝试过类似

var txt = $("body").tagName;
var txt = $("body").get();
var txt = $("body").nodeName;
var txt = new String($("body").tagName);

等等。
每次我尝试其中一个时,它要么返回节点对象本身,要么返回未定义。 如何获取它以便我可以返回诸如 body 或

之类的字符串而不是对象本身?
就此而言,我将如何获取作为字符串返回的属性的名称和值?

【问题讨论】:

    标签: jquery dom jquery-selectors introspection tagname


    【解决方案1】:

    如果要查看 jQuery 对象的 DOM 属性,则需要使用 get(n) 从 jQuery 对象中获取原始 DOM 节点,其中 n 是 jQuery 对象中的第 n 个元素。

    nodeName 将为您获取大写的节点名称,getAttribute('attributeName') 或简单的.attributeName 可用于获取属性的值。

    // Contrived example; returns BODY
    var n = document.body.nodeName;
    
    // Get the value of an attribute from an element
    var n = document.getElementById('id').title;
    
    // Unsupported attribute's value need to be obtained through `getAttribute`
    var n = document.getElementById('id').getAttribute('placeholder');
    

    查看此表以获取 DOM 函数和属性的完整列表:http://www.quirksmode.org/dom/w3c_core.html

    【讨论】:

      【解决方案2】:

      要获取标签名称,您可以使用:$("body")[0].tagName;

      要获取对象中元素的属性,您可以使用:$("body")[0].attributes;遍历该对象以获取键/值对。

      【讨论】:

        【解决方案3】:

        var txt = $("body")[0].tagName;

        注意:它会以大写字母返回 tagName。

        【讨论】:

        • "注意:它会以大写字母返回 tagName。"大概吧。
        【解决方案4】:

        document.getElementsByTagName("div")[0].tagName 用于通用。

        【讨论】:

          【解决方案5】:

          使用 jQuery 你可以像这样获取对象的标签:

          var txt = $("body").attr("tagName"); //returns "BODY" (uppercase)
          

          对于任何其他属性,请插入属性名称:

          var txt = $("div").attr("class"); //returns class of the div
          var txt = $("a").attr("title"); //returns title of the anchor
          

          这里是 .attr() 方法的文档:http://api.jquery.com/attr/

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2017-07-30
            • 2021-03-12
            • 2021-11-04
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多