Solved

jQuery, selector question

Posted on 2015-01-27
6
82 Views
Last Modified: 2015-01-27
I was just trying to do an exercise from a book. My objective is to make a table of contents based on <h2> and <h3> tags within the HTML document, but I'm trying to pull out the text() of each element first to see if I can even pull them out in the order they're listed on the page. Here is the code snippet:

<!DOCTYPE html>
<html>
    <head>
        <title></title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
        <script>
            $(function() {
                $("h2").each(function() {
                   console.log($(this).text()); 
                   /* This is my problem. I can't just use $("h3") because that will 
                        pull ALL <h3> tags. I just want to get the <h3> child of this particular <h2>. 
                        What is the syntax? */
                   $("h3").each(function() {
                      console.log($(this).text()); 
                   });
                });
            });
        </script>
    </head>
    <body>
        <h1>Title</h1>
        <div id="tocDiv">
            <ul id="tocList">
            </ul>
        </div>
        
        <h2>Chapter 1</h2>
            <h3>Section 1.1</h3>
        <h2>Chapter 2</h2>
            <h3> Section 2.1</h3>
        <h2>Chapter 3</h2>
            <h3>Section 3.1</h3>
            <h3>Section 3.2</h3>
    </body>
</html>

Open in new window


The way I was approaching it was to get all the <h2> FIRST, and then get the <h3> tags that are its children. So I approach this by getting references to all <h2> tags first, then with a nested .each() loop, try to access the <h3> child/children.

But here's my problem. In the inner .each() loop, I have to use $(this) to reference the <h2> element, but I don't know the syntax on how to create a selector that uses $(this) along with a string to get its <h3> child/children. How do I do that?

Thanks.
0
Comment
Question by:elepil
  • 3
  • 2
6 Comments
 
LVL 38

Expert Comment

by:Tom Beck
ID: 40573868
You could say
$("h2").children("h3").each(function(){
    ...
});

Or

$("h2 h3").each(function(){
    ...
});

Or, to get only immediate h3 descendants of h2

$("h2 > h3").each(function(){
    ...
});

$(this) would then refer to the h3 element.
0
 

Author Comment

by:elepil
ID: 40573903
Tom, thanks for responding.

Did you even try your suggestions with the code snippet I provided? None of your suggestions work.

Let me explain more what I'm expecting.

The first iteration of the outer .each() loop gets the reference to the FIRST <h2>, and it is immediately followed by another .each() loop to get it's single <h3> child. Then on the second iteration of the outer .each() loop, it gets the reference to the SECOND <h2>, then the inner loop is supposed to return the text() of its single <h3> child. On the third iteration, the outer .each() loop would get the THIRD <h2>, and the inner loop would then get its two <h3> children. You see what I'm trying to do?
0
 

Author Comment

by:elepil
ID: 40573913
Tom, you know what's weird?

console.log($("h2 h3").length) returns 0. That should've returned 4, not sure why that's not coming back with any results.
0
3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

 
LVL 44

Accepted Solution

by:
Rainer Jeschor earned 500 total points
ID: 40573954
Hi,
this is a really tricky one. Why? The issue is that they are on the same level, so no children, descendents whatever will work.
Here a working sample:
$(function() {
                $("h2").each(function() {
                   //console.log($(this).text()); 
                    $("#cons").append("<li>H2"+$(this).text()+"</li>");
                   /* This is my problem. I can't just use $("h3") because that will 
                        pull ALL <h3> tags. I just want to get the <h3> child of this particular <h2>. 
                        What is the syntax? */
                   $(this).nextUntil("h2","h3").each(function() {
                      //console.log($(this).text()); 
                       $("#cons").append("<li>H3"+$(this).text()+"</li>");
                   });
                });
            });

Open in new window


Live version here:
http://jsfiddle.net/EE_RainerJ/0v3w9dr0/

For better visibility I used a UL / LI for output.

HTH
Rainer
0
 
LVL 44

Expert Comment

by:Rainer Jeschor
ID: 40573960
Addition:
The first iteration of the outer .each() loop gets the reference to the FIRST <h2>, and it is immediately followed by another .each() loop to get it's single <h3> child
The H3 are NOT childs. They are next elements but on the same level.
0
 

Author Closing Comment

by:elepil
ID: 40574005
Haha, I got fooled by the indentation, made me treat the <h3> as if they were children when they weren't. Thanks for your help!
0

Featured Post

Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

PROBLEM: The other day I was working on adding an ajax request to a webpage that already had a dialog box on the page.  The dialog box was using relative positioning to be positioned next to a form field I had on the page.  Everything was working…
This article discusses how to create an extensible mechanism for linked drop downs.
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

832 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question