Search code examples
javascriptjquerysvgjquery-selectorsselectors-api

querySelector() - first inner element


I'm using SVG.js select() function which uses querySelector() function.

Currently, the command I use is: select("[id='1']") (1 could be replaced by some other number)

What I'd like to do is to select the first inner element inside this element. Alternatively, I could select it by tag name.

How to do it?

I tried select("[id='1']:first") but received an error.

By the way, the reason I select it like that is that apparently querySelector has a problem with id's which are numbers.


Solution

  • :first is a jQuery thing. For what you're doing, you can use :first-child, which is a CSS thing:

    select("[id='1'] > :first-child");
    

    That selector matches all elements that are the first child of elements with id="1", but if select is using querySelector under the covers, you'll get the first such element.

    Note that the > in that is the child combinator: It means we're looking for :first-child within [id='1']. (An earlier version of this answer used [id='1'] :first-child, which uses a descendant combinator [just whitespace]. It would matter for selecting a list of elements, but not if selecting only on the first match.) (You need one or the other, since without any combinator ([id='1']:first-child) it would b elooking for the first [id='1'] that was also a :first-child.)