【问题标题】:Getting HTML elements by their attribute names通过属性名称获取 HTML 元素
【发布时间】:2011-11-30 14:49:52
【问题描述】:

JavaScript 中有一些方法可以使用它们的 ID、类和标记来获取 HTML 元素。

document.getElementByID(*id*);
document.getElementsByClassName(*class*);
document.getElementsByTagName(*tag*);

有没有什么方法可以根据属性名获取元素。

前:

<span property="v:name">Basil Grilled Tomatoes and Onions</span>

喜欢:

document.getElementsByAttributeName("property");

【问题讨论】:

  • 你能详细说明为什么你需要这样做吗?这是非常低效的,有更好的方法来解决它。

标签: javascript html dom


【解决方案1】:

是的,函数是querySelectorAll(或querySelector,用于单个元素),它允许您使用 CSS 选择器来查找元素。

document.querySelectorAll('[property]'); // All with attribute named "property"
document.querySelectorAll('[property="value"]'); // All with "property" set to "value" exactly.

(Complete list of attribute selectors on MDN.)

这会找到所有具有属性属性的元素。如果可能,最好指定一个标签名称:

document.querySelectorAll('span[property]');

如有必要,您可以通过遍历页面上的所有元素以查看它们是否具有属性集来解决此问题:

var withProperty = [],
    els = document.getElementsByTagName('span'), // or '*' for all types of element
    i = 0;

for (i = 0; i < els.length; i++) {
    if (els[i].hasAttribute('property')) {
        withProperty.push(els[i]);
    }
}

诸如 jQuery 之类的库会为您处理这个问题;让他们做繁重的工作可能是个好主意。

对于任何处理古老浏览器的人,请注意querySelectorAll 在 v8 (2009) 中被引入 Internet Explorer,并在 IE9 中得到完全支持。所有modern browsers都支持。

【讨论】:

  • 我相信您需要在属性值周围加上双引号。 document.querySelectorAll('[property=value]');应该是 document.querySelectorAll('[property="value"]');
  • 太棒了。谢谢
【解决方案2】:

在 jQuery 中是这样的:

$("span['property'=v:name]"); // for selecting your span element

【讨论】:

  • 他使用的是原生 Javascript,所以在这种情况下他可能不会尝试使用 jQuery :)
【解决方案3】:

只是另一个答案

Array.prototype.filter.call(
    document.getElementsByTagName('span'),
    function(el) {return el.getAttribute('property') == 'v.name';}
);

未来

Array.prototype.filter.call(
    document.getElementsByTagName('span'),
    (el) => el.getAttribute('property') == 'v.name'
)

第三方编辑

简介

  • call() method 使用给定的 this 值和单独提供的参数调用函数。

  • filter() method 创建一个新数组,其中包含所有通过所提供函数实现的测试的元素。

鉴于此 html 标记

<span property="a">apple - no match</span>
<span property="v:name">onion - match</span>
<span property="b">root - match</span>
<span property="v:name">tomato - match</span>
<br />
<button onclick="findSpan()">find span</button>

你可以使用这个javascript

function findSpan(){

    var spans = document.getElementsByTagName('span');
    var spansV = Array.prototype.filter.call(
         spans,
         function(el) {return el.getAttribute('property') == 'v:name';}
    );
    return spansV;
}

demo

【讨论】:

  • 如何使用/调用函数?
  • 你可以像我写的那样调用,只需将结果分配给一个变量。然而,5 年后,我认为@paula-fleck 的答案会更好。
【解决方案4】:

你可以使用querySelectorAll:

    document.querySelectorAll('span[property=name]');

【讨论】:

    【解决方案5】:

    我想你想看看jQuery,因为那个 Javascript 库提供了很多你可能想在这种情况下使用的功能。在您的情况下,您可以编写(或在互联网上找到)一个 hasAttribute 方法,如下所示(未测试):

    $.fn.hasAttribute = function(tagName, attrName){
      var result = [];
      $.each($(tagName), function(index, value) { 
         var attr = $(this).attr(attrName); 
         if (typeof attr !== 'undefined' && attr !== false)
            result.push($(this));
      });
      return result;
    }
    

    【讨论】:

      【解决方案6】:

      您可以使用javascript获取属性,

      element.getAttribute(attributeName);
      

      例如:

      var wrap = document.getElementById("wrap");
      var myattr = wrap.getAttribute("title");
      

      参考:

      https://developer.mozilla.org/en/DOM/element.getAttribute

      【讨论】:

        【解决方案7】:

        使用 prototypejs

         $$('span[property=v.name]');
        

        document.body.select('span[property=v.name]');
        

        两者都返回一个数组

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2012-11-17
          • 2011-07-30
          • 2012-01-13
          • 2016-02-25
          • 1970-01-01
          • 1970-01-01
          • 2014-03-21
          相关资源
          最近更新 更多