user319940
user319940

Reputation: 3317

Foreach in jQuery

I'm trying to prepend a tag to each h2 based on the content that specific h2. Here's what I've tried:

jQuery(document).ready(function() {
    jQuery( "h2" ).each(function(){
        var $headingcontent = jQuery('h2').html().toLowerCase();
        jQuery('h2').prepend('<a id="'+ $headingcontent +'"></a>');
    });
});

However, this seems to only get the content of the first h2 and prepend it to every h2, it does this multiple times depending on how many h2's are on the page.

What I would like it to do is turn this:

<h2>Heading 1</h2>
<h2>Heading 2</h2>

in to

<h2><a id="heading 1"></a>Heading 1</h2>
<h2><a id="heading 2"></a>Heading 2</h2>

Upvotes: 1

Views: 638

Answers (3)

Sam Jones
Sam Jones

Reputation: 4618

First i'd make sure it only applies to the H2's you intend, down the line you/someone else may add a h2 somewhere else and get unexpected results...

<h2 class='content'>Heading 1</h2>
<h2 class='content'>Heading 2</h2>

code:

jQuery(document).ready(function() {
    jQuery('h2.content').each(function(){
var target = $(this);
        jQuery(target).append($('<a/>',{'id':$(target).text(),text:$(target).text()}));
    });
});

Upvotes: 0

raam86
raam86

Reputation: 6871

I would instead nest the anchor inside the H2 element.

$( "h2" ).each(function(_,el){//Get each element as el and _ as index
    el = $(el); // Cache for performance
    var $headingcontent = el.text().toLowerCase();//Get the text
    //Replace h2 content with the an anchor element with same content;
    el.html('<a id="'+ encodeURIComponent($headingcontent) +'">' 
    + $headingcontent
    + '</a>');
});

and ofcourse you don't need I\anchor element at all

$( "h2" ).each(function(_,el){//Get each element as el and _ as index
    el = $(el); // Cache for performance
    var $headingcontent = el.text().toLowerCase();/Get the text
   //Add id to element for navigational purposes.
    el.prop('id', encodeURIComponent($headingcontent));
});

Upvotes: 2

zerkms
zerkms

Reputation: 254886

jQuery( "h2" ).each(function(){
    var $headingcontent = jQuery(this).html().toLowerCase();
    jQuery(this).prepend('<a id="'+ $headingcontent +'"></a>');
});

Btw, you don't need an additional a element at all:

jQuery( "h2" ).each(function(){
    var $this = jQuery(this);
    $this.attr('id', $this.html().toLowerCase());
});

Upvotes: 6

Related Questions