parent and child elements and thier text

There are some situations where you have to get immediate parent and immediate child elements and thier text of a particular element.

 

Here I am expaling about how to display parent and child elements of a particular element. Below is the sample code to fulfill our requirement.

 

<html>
    <head>
        <title>This is jquery example to display immediate and imeediate childs content</title>
        <script type="text/javascript" src="jquery.js"></script>
        <script type="text/javascript">
            $(document).ready(function() {
            //it will display immediate parent text
            alert($('#childid').parent().text());

            //it will display all childs text
            alert($('#childid').children().text());
            });   
        </script>
    </head>
    <body>
        <div id="parentid">
            <div id="childid">
                <div>First Element</div>
                <div>Second Element</div>
                <div>Third Element</div>
                <div>Fourth Element</div>
            </div>
            <p id="pid">This is from 'p' tag</p>
        </div>
    </body>
</html>

 

In the above code parent() jQuery function is used to get the immediat parent and children() jQuery function is used to get the immediate child elements.

$('#childid').parent().text() is used to get the text of immediate parent of element whose id is "childid".

$('#childid').children().text() is used to get the text of immediate childs of element whose id is "childid".

 

Download source code: fourth jQuery exmp.zip (35.72 kb)