Thứ Tư, 20 tháng 11, 2013

GET ELEMENT BY ATTRIBUTE VALUE

GET ELEMENT BY ATTRIBUTE VALUE (PLAIN JAVASCRIPT)

Just a quick and simple function to grab any one element by a certain attribute value, without having to use libraries like jQuery or Prototype:

function getElementByAttributeValue(attribute, value) { 
       var allElements = document.getElementsByTagName('*'); 
       for (var i = 0; i < allElements.length; i++) {
            if (allElements[i].getAttribute(attribute) == value) {   
               return            allElements[i]; 
            }
       }
 }

In case of multiple elements with the same attributes this will only return the first one.
EXAMPLE

Sometimes I use elements like <header role="masthead"> in my site to be able to style the site's header (masthead) differently than other header elements, for example post headers. To select this element in JavaScript I'd now use:var headerElement = getElementByAttributeValue('role', 'masthead');

Không có nhận xét nào:

Đăng nhận xét