How to use child selectors in Javascript?


Please briefly explain why you feel this question should be reported .

Report Cancel

Suppose I have a div like:

<div class="parent">

<p class="child">Hello1</p>

<p class="child">Hello2</p>

<p class="child">Hello3</p>


Using JavaScript, how can I select the second child of the parent?

solved 0 1 Answer 4775 views Beginner 1

About the AuthorBeginner

Answer ( 1 )

    March 16, 2016 at 7:43 am

    Please briefly explain why you feel this answer should be reported .

    Report Cancel

    Using javascript  you can do, but it is recommended to use Jquery to reduce the code.

    For instance using Javascript :
    function findMatches(){
    var matches = [];
    var searchEles = document.getElementsByClassName(“parent”)[0].children;
    for(var i = 0; i < searchEles.length; i++) {
    if(searchEles[i].tagName == ‘P’) {
    if(searchEles[i].getAttribute(‘class’) == ‘child’) {

    In this case, all the matches corresponding to the parent element will be returned.
    When in Jquery, your function will be like this :
    function findMatches(){
    return $(‘.parent’).find(‘.child’);

    I would personally recommend to use jquery for these operations because of lesser code and compressed javascript output on browser.

    Best answer

Leave an answer