MJ
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>
Thanks!
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);
}
}
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;
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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 ==>
@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) {
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
Working sample here
Note the above solution is more performant than using XPath which can be expensive
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;
}
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
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