Get element by attribute value (plain Javascript)

Posted by on

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

3 Responses to “Get element by attribute value (plain Javascript)”

  1. baptiste said on

    Hello, thanks for you script but i have a question.

    Is it possible to return the closest element instead of the first element ?

    Thx

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>