Getting HTML elements by their attribute names

后端 未结 7 619
南方客
南方客 2020-12-07 22:06

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

document.getElementByID(*id*);
document.getElementsByClassName(         


        
相关标签:
7条回答
  • 2020-12-07 22:31

    You can use querySelectorAll:

        document.querySelectorAll('span[property=name]');
    
    0 讨论(0)
  • 2020-12-07 22:38

    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;
    }
    
    0 讨论(0)
  • 2020-12-07 22:40

    In jQuery this is so:

    $("span['property'=v:name]"); // for selecting your span element
    
    0 讨论(0)
  • 2020-12-07 22:41

    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

    0 讨论(0)
  • 2020-12-07 22:54

    With prototypejs :

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

    or

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

    Both return an array

    0 讨论(0)
  • 2020-12-07 22:57

    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.

    0 讨论(0)
提交回复
热议问题