Solved

jQuery, selector question

Posted on 2015-01-27
6
78 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
What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

 
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

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Introduction A frequently asked question goes something like this:  "I am running a long process in the background and I want to alert my client when the process finishes.  How can I send a message to the browser?"  Unfortunately, the short answer …
I found this questions asking how to do this in many different forums, so I will describe here how to implement a solution using PHP and AJAX. The logical flow for the problem should be: Write an event handler for the first drop down box to get …
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…

705 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

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now