1

Alright, I've dabbled in JavaScript before, but the most useful thing I've written is a CSS style-switcher. So I'm somewhat new to this. Let's say I have HTML code like this:

<div class="first">
    <div id="bar">
        Hello world!
    </div>
</div>

Not Working:document.getElementsByClassName("first").getElementById("bar")[0];

2
  • 1
    getElementsByClassName returns an array, not a object for further querying Commented Mar 13, 2018 at 8:01
  • Despite the fact you should not use an id if you habe multiple of them, as Napoli stated getElementsByClassName returns a collection of nodes, which can't be queried further. Use document.querySelector('.first #bar') in such cases. Commented Mar 13, 2018 at 8:10

1 Answer 1

2

You might want to use document.querySelector.

With that you can use CSS selectors and do e.g.

var bar_element = document.querySelector(".first #bar");
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.