5

How do I get > p > a working in querySelector ?

<div id="container">
    <p>
        <a href="#">Link</a>
    </p>
</div>

<script type="text/javascript">    
console.log(document.getElementById("container").querySelector("> p > a"));
</script>

SyntaxError: An invalid or illegal string was specified

anjanesh
  • 3,771
  • 7
  • 44
  • 58
  • 1
    You want to translate jQuery code to pure JS? Is that it? – Fabrício Matté Jul 30 '12 at 10:07
  • possible duplicate of [When using querySelectorAll, is there a way to reference the immediate children of the context node, without using IDs?](http://stackoverflow.com/questions/11440725/when-using-queryselectorall-is-there-a-way-to-reference-the-immediate-children) – Rob W Jul 30 '12 at 10:10

1 Answers1

11

It's the leading > that's stopping you. If you're going to use querySelector you might as well get the container by that means, too, rather than using getElementById.

document.querySelector("#container > p > a")
Mitya
  • 33,629
  • 9
  • 60
  • 107
  • That's just an example, I guess. The question is stated at the first line: "How do I get `> p > a` working in querySelector?". – Rob W Jul 30 '12 at 10:12
  • Well if the query is literally that, it won't work, as you can't lead with `>`, and query selector syntax has no reference to self (it would be good if you could do something like `'_self > p > a'`. I guess you'd have to fall back to `childNodes`? – Mitya Jul 30 '12 at 10:14
  • 3
    Or just wait for `findAll` to be implemented. See the linked [duplicate question](http://stackoverflow.com/questions/11440725/when-using-queryselectorall-is-there-a-way-to-reference-the-immediate-children). – Rob W Jul 30 '12 at 10:17
  • [Deprecated these days](https://developer.mozilla.org/en-US/docs/Mozilla/Gecko/Chrome/API/Browser_API/findAll). – Mitya Feb 12 '21 at 10:19