How to use child selectors in Javascript?

Report
Question

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>

</div>

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

solved 0
asp.net 1 Answer 577 views Beginner 1

About the AuthorBeginner

Answer ( 1 )

    0
    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’) {
    matches.push(searchEles[i]);
    }
    }
    }
    }

    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