membersound
membersound

Reputation: 86727

How to get only specific tags of elementsByClassName?

<div class="dates">
  <span class="dates>value</span>
</div>

I'd like to extract all elements with class dates, but only the span elements.

How would I have to modify the following JS:

var elements = document.getElementsByClassName("dates"); //gets both div + span

Finally I'd like to extract all text values of the span tags.

I'm using the "old" getElementsByClassName to also support older browsers.

Upvotes: 1

Views: 249

Answers (2)

CodingIntrigue
CodingIntrigue

Reputation: 78525

If you can, use querySelectorAll:

var elements = document.querySelectorAll("span.dates");

Otherwise, you can use tagName to filter down your existing elements:

var elements = document.getElementsByClassName("dates");
for(var i=elements.length; i--;) {
    if(elements[i].tagName.toLowerCase() != "span") continue;
    // Do work
}

Upvotes: 2

VisioN
VisioN

Reputation: 145398

In modern browsers you may use the CSS selector with querySelectorAll:

var elements = document.querySelectorAll('div.dates, span.dates');

It is supported by the following browsers:

  • Chrome - 1
  • Firefox (Gecko) - 3.5 (1.9.1)
  • Internet Explorer - 9 and 8 (CSS2 selectors only)
  • Opera - 10
  • Safari (WebKit) - 3.2 (525.3)

Upvotes: 1

Related Questions