Solved

jQuery, selector question

Posted on 2015-01-27
6
85 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Guide to Performance: Optimization & Monitoring

Nowadays, monitoring is a mixture of tools, systems, and codes—making it a very complex process. And with this complexity, comes variables for failure. Get DZone’s new Guide to Performance to learn how to proactively find these variables and solve them before a disruption occurs.

 
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

Space-Age Communications Transitions to DevOps

ViaSat, a global provider of satellite and wireless communications, securely connects businesses, governments, and organizations to the Internet. Learn how ViaSat’s Network Solutions Engineer, drove the transition from a traditional network support to a DevOps-centric model.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
jQuery - Add confirm message to button? 2 26
Print a <div></div> only 5 39
Building JSON/JQuery Results Display 11 25
AJAx/JQuery/JSON Error 3 10
I have answered several questions lately that were solved utilizing the power of jQuery's AJAX functions, so I thought I would write an article demonstrating the ease of use. Why should I use jQuery as opposed to regular JavaScript? Now I know…
This article demonstrates how to create a simple responsive confirmation dialog with Ok and Cancel buttons using HTML, CSS, jQuery and Promises
The viewer will learn the basics of jQuery, including how to invoke it on a web page. 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.: (CODE)
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…

749 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