Brendan Brendan - 6 months ago 28
HTML Question

Grabbing a class within a class with javascript

Hello this is my first question and I'm an amateur developer so forgive me in advance. I'm trying to grab this specific instance of the value class. The website I am working on has hundreds of different values associated with the value class.

<li class = "vin">
<strong class = "title">VIN:</strong>
<span class="value">121212121212121212</span>
</li>


Below is what I've been doing and it hasn't been working.

var vinNum = document.getElementsByClassName('li.vin','span.value');
console.log(vinNum.innerText);


Thank you

Answer Source

Although the existing answers cover the "modern" way to do this already - you can use most of the getElementsBy... (all, I think - was gonna say except getElementById, but that is named in singular for a reason, and because of the meaning of an id special) methods on all elements.

https://developer.mozilla.org/en-US/docs/Web/API/Element/getElementsByClassName:

The Element.getElementsByClassName() method returns a live HTMLCollection containing all child elements which have all of the given class names. When called on the document object, the complete document is searched, including the root node.

So you can use that twice, to first select an element with one specific class, and then another with a different class "within it", among the descendants of the former. (Not "child elements", as the quoted MDN reference wrongly puts it.)

var vinNumContainer = document.getElementsByClassName('vin')[0],
    vinNumElement   = vinNumContainer.getElementsByClassName('value')[0];

(Necessary checks for whether elements exist before accessing them, what to do if more than one element (of either one) exists, etc., left out for brevity ;-)

But a simple call to querySelector is of course a quicker way to do it.