Tahsis Claus
Tahsis Claus

Reputation: 1929

Select node from children by attribute

I have an interface that switches between displaying different div elements. When it switches which element it displays, I need to access a specific child node of that div element, with each div element having their children arranged differently.

The childNodes and children property both return an object that can only select children with item(index) which is annoying to use as the relevant child element's index is different in each div. For Protractor, I used the webmanager.by(selector) which was able to search with other parameters than index. Is there something similar I can use to select the child node with data-relevant="true". I am also unsure if that attribute is the best way to specify in the HTML which child node is relevant.

This is an Angular application if that helps.

Upvotes: 4

Views: 3044

Answers (1)

S.Frank
S.Frank

Reputation: 86

If you want to select the child node with data-relevant="true" from some parent element, you could use the selector method

element.querySelector()
That would return the first matching element...

in your specific case it could be something like

parent-element.querySelector( "[data-relevant='true']" );

or if you want to select all paragraphs p with the data-relevant attribute value true within the parent div: parentDiv.querySelectorAll( "p[data-relevant='true']" );

You can find some examples on http://www.w3.org/TR/selectors-api/#processing-selectors

An alternative would be to use a special class to identify which child node is relevant... you could get this element/or many elements with getElementsByClassName(someClassName)

Code Sample With .querySelectorAll() method:

<script type="text/javascript">

    window.addEventListener("load", init, false);

function init(){
    var parentDiv = document.getElementById("divWithChildren");
    var relevantChildren = parentDiv.querySelectorAll( "[data-relevant='true']" );
    alert (relevantChildren[2].id); // this will give the id of the 3rd child element with data-relevant='true'
}

</script>

Upvotes: 5

Related Questions