Search code examples
javascriptregexgetattribute

javascript getattribute method with regex


<div id="foo" platform="bar" table-index="1">
  hello!
</div>

if i use getAttribute method and get value, it'll be like this

var ele = document.querySelector("#foo").getAttribute("platform")

and i can get "bar" by ele variable.

but i wanna use getAttribute with regular expression.

var ele = document.querySelector("#foo").getAttribute(`regex contains just "index"`)

word "table-index" end with index. so i wanna find attribute and get 1(table-index value) just use "index" and regex.

i have no idea way to use regex in attiributeName.


Solution

  • getAttribute cannot be used in this manner-- it accepts a string for an argument, not a regex. However, you could implement a way of doing something similar. The below approach works by using the [attributes] property of an element and then iterating over them, searching for one that is matched by the regex, and then returning that value.

    Note that this particular implementation naively assumes that you are using a regex that will match only a single attribute on the element and will return the first match it encounters-- however, you could be more clever and write something more robust that returns an array of matched attribute/value pairs.

    function getAttributeByRegex(element, regex) {
      const attributes = element.attributes;
      for (let i = attributes.length - 1; i >= 0; i--) {
        const attr = attributes[i];
        if (regex.test(attr.name)) {
          return attr.value;
        }
        return undefined;
      }  
    }
    
    const value = getAttributeByRegex(
      document.querySelector('#foo'),
      /-index/
    );
    
    console.log(value);
    <div id="foo" platform="bar" table-index="1">
      hello!
    </div>