tags:

views:

78

answers:

4

Hi,

I'm using latest jQuery (via the Google CDN) and am using this code to build a TOC:

$("#infoArticles h2, #infoArticles h3").each(function(i) {
    var current = $(this);
    current.attr("id", "title" + i);
    $("#toc").append("<li><a id='link" + i + "' href='#title" + i + "' title='" + current.attr("tagName") + "'>" + current.html() + "</a></li>");
});

Works a treat.

I want the .each loop to treat matched h2's differently from matched h3's in order that I may add a class to the li's resulting from h2's.

Any helpful comments, most appreciated and gratefully received!

+1  A: 

Check the nodeName or tagName.

$("h2").each(function(i){
  alert(this.nodeName + " " + i); // Alerts 'H2 0,' 'H2 1,' etc.
});
Jonathan Sampson
Thanks for your answer!
Alan
+1  A: 
$("#infoArticles h2, #infoArticles h3").each(function(i) {
    var current = $(this);
    current.attr("id", "title" + i);
    if(this.tagName == "H2"){
      //h2
    }else{
      //h3
    }
    $("#toc").append("<li><a id='link" + i + "' href='#title" + i + "' title='" + current.attr("tagName") + "'>" + current.html() + "</a></li>");
});
Marius
Thanks for your answer!
Alan
A: 

You create a function out of your code and call it with different parameters:

$("#infoArticles h2").each(function(i) {
    myFunction("ma-classe");
});
$("#infoArticles h3").each(function(i) {
    myFunction();
});

function myFunction(class=""){
   var current = $(this);
    current.attr("id", "title" + i);
    $("#toc").append("<li class='"+class+"'><a id='link" + i + "' href='#title" + i + "' title='" + current.attr("tagName") + "'>" + current.html() + "</a></li>");
}
Guillaume Flandre
Thanks for your answer!
Alan
A: 

Note that Append is expensive, so, for the sake of optimisation, you should move the append() function out of your loop, to only do it once instead of for each selected element.

var htmlToInsert = null;
$("#infoArticles h2, #infoArticles h3").each(function(i) {
    var current = $(this);
    current.attr("id", "title" + i);
    if(this.tagName == "H2"){
      //h2
    }else{
      //h3
    }
    htmlToInsert += "<li><a id='link" + i + "' href='#title" + i + "' title='" + current.attr("tagName") + "'>" + current.html() + "</a></li>";

});
$("#toc").append(htmlToInsert);
pixeline
Thanks and thanks for alerting me to Append.
Alan