farhang
farhang

Reputation: 407

Jquery: dynamic change anchor data-attr if needed

I have a tiny jQuery function to add an id to each header (for the sake of using as anchor in a TOC).

$(":header").each(function() {
    let eachID = $(this)
    .text()
    .toLowerCase()
    .replace(/[^\w ]+/g, "")
    .replace(/ +/g, "-");
    $(this).attr({ id: eachID });
});

It works as needed. <h1>Hello World</h1> becomes <h1 id="hello-world">Hello World</h1>.

I am having trouble with possible repeated/duplicated headers.

I found many answers on SO and the closest is this one.

The small trouble with that one is that it adds a +1 to all headers after the first and not just the duplicated one.

In this codepen, you can see that <h2>Hello World</h2> is properly changed to <h2 id="hello-world2">Hello World</h2>, but so is <h1>So long World</h1>, even though it does not need to be changed.

Any help would be appreciated.

Upvotes: 2

Views: 66

Answers (1)

Sushanth --
Sushanth --

Reputation: 55750

One way around it using document.querySelectorAll ( $(idSelector) always returns the first element with the id as ids are supposed to be unique on a page anyways ) to get list of elements with a particular id and check for its length.

Ideally you would not want to do that.

$(':header[id]').not(':eq(0)').each(function(i){ 
    var $that = $(this);
      var currentId = $that.attr('id');
      var elemsWithId = document.querySelectorAll('#' + currentId);

      if(elemsWithId.length > 1) {
         var newID = currentId + (i + 1);
         $that.attr('id', newID);
      }
});

Codepen

Upvotes: 2

Related Questions