通过属性名称获取 HTML 元素

发布于 2024-12-07 23:53:02 字数 419 浏览 0 评论 0原文

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

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

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

例如:

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

喜欢:

document.getElementsByAttributeName("property");

There are methods available in JavaScript to get HTML elements using their ID, Class and Tag.

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

Is there any method available to get the elements according to the attribute name.

EX:

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

Like:

document.getElementsByAttributeName("property");

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

淡紫姑娘! 2024-12-14 23:53:02

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

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

(MDN 上属性选择器的完整列表。)

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

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 中得到完全支持。所有现代浏览器都支持它。

Yes, the function is querySelectorAll (or querySelector for a single element), which allows you to use CSS selectors to find elements.

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.)

This finds all elements with the attribute property. It would be better to specify a tag name if possible:

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

You can work around this if necessary by looping through all the elements on the page to see whether they have the attribute set:

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]);
    }
}

Libraries such as jQuery handle this for you; it's probably a good idea to let them do the heavy lifting.

For anyone dealing with ancient browsers, note that querySelectorAll was introduced to Internet Explorer in v8 (2009) and fully supported in IE9. All modern browsers support it.

七婞 2024-12-14 23:53:02

假设您有一个输入:

         <input type='text' name='from'/>
  

那么您可以按如下方式访问它:

        document.querySelector('input[name="from"]')

Let's assume that you have an input:

         <input type='text' name='from'/>
  

then you can access it as follow:

        document.querySelector('input[name="from"]')
停顿的约定 2024-12-14 23:53:02

您可以使用querySelectorAll

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

You can use querySelectorAll:

    document.querySelectorAll('span[property=name]');
北方的巷 2024-12-14 23:53:02

在 jQuery 中是这样的:

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

In jQuery this is so:

$("span['property'=v:name]"); // for selecting your span element
凉栀 2024-12-14 23:53:02

只是另一个答案

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'
)

第 3 方编辑

介绍

鉴于此 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;
}

请参阅 演示

Just another answer

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

In future

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

3rd party edit

Intro

  • The call() method calls a function with a given this value and arguments provided individually.

  • The filter() method creates a new array with all elements that pass the test implemented by the provided function.

Given this html markup

<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>

you can use this 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;
}

See demo

一杯敬自由 2024-12-14 23:53:02

我想你想看看 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;
}

I think you want to take a look at jQuery since that Javascript library provides a lot of functionality you might want to use in this kind of cases. In your case you could write (or find one on the internet) a hasAttribute method, like so (not tested):

$.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;
}
尹雨沫 2024-12-14 23:53:02

您可以使用 javascript 获取属性,

element.getAttribute(attributeName);

例如:

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

请参阅:

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

You can get attribute using javascript,

element.getAttribute(attributeName);

Ex:

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

Refer:

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

云醉月微眠 2024-12-14 23:53:02

使用 prototypejs

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

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

两者返回一个数组

With prototypejs :

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

or

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

Both return an array

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文