0

In javaScript, how is the best way to get a specific html node where I know the attribute name and attribute value, and many html nodes can have the same attribute name? The attribute name is a data attribute.

Here is some example html:

<div class="misc1" data-test="value1" data-test="value2"></div>
<div class="misc2" data-test="value3" data-test="value4"></div>

If I want to get the html node with data-test="value3", do I need to do something along the lines of:

  var elements = document.querySelectorAll("[data-test]");
  for (i = 0; i < elements.length; i++) {
    for(x = 0; x < elements[i].attributes.length; x++) {
        //Do an attribute value check??
    }
  }

Can I please have some help with the code and I would not like to use jQuery?

1 Answer 1

3

Your attribute selector can be made more specific like so:

var elements = document.querySelectorAll('[data-test="value3"]');

There are multiple other variations of the attribute selector as well:

  • [attr] Represents an element with an attribute name of attr.
  • [attr=value] Represents an element with an attribute name of attr and whose value is exactly "value".
  • [attr~=value] Represents an element with an attribute name of attr whose value is a whitespace-separated list of words, one of which is exactly "value".
  • [attr|=value] Represents an element with an attribute name of attr. Its value can be exactly “value” or can begin with “value” immediately followed by “-” (U+002D). It can be used for language subcode matches.
  • [attr^=value] Represents an element with an attribute name of attr and whose value is prefixed by "value".
  • [attr$=value] Represents an element with an attribute name of attr and whose value is suffixed by "value".
  • [attr*=value] Represents an element with an attribute name of attr and whose value contains at least one occurrence of string "value" as substring.
  • [attr operator value i] Adding an i before the closing bracket causes the value to be compared case-insensitively (for characters within the ASCII range).
Sign up to request clarification or add additional context in comments.

2 Comments

this is correct answer, I always feel it necessary though to see if OP is intentionally trying to avoid jQuery , or just don't realize how much easier stuff like this is
@ScottSelby Sorry about that :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.