Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding Element By Property/Attribute

Given the following

  ...
     <tr xyz="Alpha"> ... </tr>
     <tr xyz="Bravo"> ... </tr>
     <tr xyz="Delta"> ... </tr>
  ...

how can I get the row having xyz = "Bravo" in JScript, aside from just creating a getElementsByTagName() loop, and testing each returned element for it?

Is xyz an attribute, or a property?

like image 937
Brian Wren Avatar asked Apr 01 '14 17:04

Brian Wren


People also ask

How do you find the element of a property?

Use the querySelector() method to get a DOM element by attribute, e.g. document. querySelector('[data-id="first"]') . The querySelector method will return the first element in the document that matches the specified attribute.

How do you select an element by attribute?

The [attribute|="value"] selector is used to select elements with the specified attribute, whose value can be exactly the specified value, or the specified value followed by a hyphen (-). Note: The value has to be a whole word, either alone, like class="top", or followed by a hyphen( - ), like class="top-text".

How do I find attributes in DOM?

HTML DOM getAttribute() method is used to get the value of the attribute of the element. By specifying the name of the attribute, it can get the value of that element. To get the values from non-standard attributes, we can use the getAttribute() method.

How do you get attribute values in Cypress?

To find elements by data attribute, query using the attribute selector. cy. get() yields a jQuery object, you can get its attribute by invoking the . attr() method.


1 Answers

No xyz isn't a valid attribute or property, but data attributes introduced in HTML5 are valid .

You can use them like this:

     <tr data-xyz="Alpha"> ... </tr>
     <tr data-xyz="Bravo"> ... </tr>
     <tr data-xyz="Delta"> ... </tr>

Then you can use .querySelector() to find a particular element.

document.querySelector('[data-xyz="Bravo"]');

If you want to limit searching to tr alone, then do this:

document.querySelector('tr[data-xyz="Bravo"]');
like image 168
Amit Joki Avatar answered Oct 01 '22 12:10

Amit Joki