Gabriel
Gabriel

Reputation: 611

how to use querySelector to select dynamic added elements

I have a dom like this:

<ul>
   <li><a>test</a></li>
   <li><a>test</a></li>
   <li><a>test</a></li>
   <li><a>test</a></li>
</ul>

the <li> element are added to the html dynamically so that I cannot add id to it. And I'm using css selector to select the <li> element by using:

document.querySelector("li:nth-child(1)")

But how can I select the <a> element inside the <li>? Can I do a querySelector inside anther querySelector? Or there's some better ways to do it? Thanks.

Upvotes: 3

Views: 15413

Answers (3)

Ankit Rathore
Ankit Rathore

Reputation: 46

document.querySelector("li:nth-child(1) a"); 

Will work

Upvotes: 0

Quentin
Quentin

Reputation: 944171

But how can I select the <a> element inside the <li>?

Selector syntax includes the descendant combinator, which is a space

document.querySelector("li:nth-child(1) a")

Can I do a querySelector inside anther querySelector?

The querySelector method appears on all HTML elements. You can chain them:

document.querySelector("li:nth-child(1)").querySelector('a');

… which you probably shouldn't in this case.

If you were selecting multiple elements (with querySelectorAll) then this would be less viable as you would have to loop over the first set of results and then query the descendants of each one.

Using native selector syntax is usually easier and clearer.

Upvotes: 4

Adam Jenkins
Adam Jenkins

Reputation: 55782

Can I do a querySelector inside anther querySelector?

Yes

document.querySelector('li:nth-child(1)').querySelector('a');

Or there's some better ways to do it?

Yes

document.querySelector('li:nth-child(1) a');

Upvotes: 1

Related Questions