Link to home
Start Free TrialLog in
Avatar of MJ
MJFlag for United States of America

asked on

JavaScript - Get Value from Multiple Span Tags With Same Class?

Using javascript only (no jQuery) I have multiple span tags with the same class. I want to grab the innerHTML for this specific element so I can get the request ID ==> E4230
<span class="need-help-section"> Your Online Request ID is: <br> <strong>E4230</strong> </span>

Open in new window

Thanks!
Avatar of leakim971
leakim971
Flag of Guadeloupe image

what is the difference between this one and the other?
Try below code:

var inputId = 'E4230';
        var allSpans = document.getElementsByClassName('need-help-section');
        for (var i = 0; i < allSpans.length; i++) {
            if (allSpans[i].innerHTML && allSpans[i].innerHTML.indexOf(inputId) != -1) {
                alert(allSpans[i].innerHTML);
            }
        }

Open in new window

This will find all <span>'s with class need-help-section and extract their ids - returning an array of all ids
function getHelpSectionIds() {
  var els = document.getElementsByClassName('need-help-section');
  var ids = [];
  for(var e of els) {
    var match = e.textContent.match(/(E(\d+))/);
    if (match) {
      ids.push(match[0]);
    }
  }
  return ids;
}

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of leakim971
leakim971
Flag of Guadeloupe image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of MJ

ASKER

@Mrunal - I will not know the ID so I can't specify it.

@Julian - I'm getting an unexpected identifier on this line of your code when I tried to save the file ==>
 for(var e of els) {

Open in new window

Avatar of MJ

ASKER

Thank you all!
you welcome!
I suspect you were using IE11 - the solution I provided works in all other browsers including Edge?

Here is a version that works for that browser as well
function getHelpSectionIds() {
  var els = document.getElementsByClassName('need-help-section');
  var ids = [];
  
  for(var i = 0; i < els.length; i++) {
    var e = els[i];
    var match = e.textContent.match(/(E(\d+))/);
    if (match) {
      ids.push(match[0]);
    }
  }
  return ids;
}

Open in new window


Working sample here
Note the above solution is more performant than using XPath which can be expensive
document.querySelector is OK on "all" browser (IE>=8)
https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector#Browser_compatibility

document.evaluate is not supported by IE but Edge Chromium (version >= 12) is fine :
https://developer.mozilla.org/en-US/docs/Web/API/Document/evaluate#Browser_compatibility

User generated image
User generated image