WitVault WitVault - 22 days ago 8
CSS Question

Select sibling dom element based on the text content of one of sibling

I have following html structure -

<p>
<span class="font-weight-medium">
Phone Number:
</span>
<br>
<span>(123) 456-7869</span>
</p>


Now I want to select all such span which have phone number using pure javascript or css selector.
I am using x-ray.
I had tried this but this doesn't seems to work.

x(html,'span[contains(text(),"Phone Number")]')
(function(err, obj) {
console.log(obj);
});

Answer

You can get all span elements and loop to find next span after those containing Phone Number:

span_tags = document.getElementsByTagName('span');
for (var i=0, max=span_tags.length; i < max; i++) {
  el =  span_tags[i];
  str = el.innerHTML;
  regex = / *Phone Number: */;
  if ( str.match(regex)) {
    console.log(span_tags[i+1].innerHTML);
  }
}
<p>
  <span class="font-weight-medium">
Phone Number:
  </span>
  <span>(123) 456-7869</span>
</p>

I'm not sure there is a css selector based solution (:contain is a jquery pseudo selector). But here is another approach using indexOf:

span_tags = document.getElementsByTagName('span');
for (var i=0, max=span_tags.length; i < max; i++) {
  if (span_tags[i].innerHTML.indexOf("Phone Number:") != -1) {
   console.log(span_tags[i+1].innerHTML);
  }
}
<p>
  <span class="font-weight-medium">
Phone Number:
  </span>
  <span>(123) 456-7869</span>
</p>