user2138489
user2138489

Reputation: 75

find all header tags and check each tag has id attribute and if not add id attribute using jquery

Want to find all header tags from the content and check each tag has id attribute and if not, then add id attribute using jquery

Below is my code:

var headings = $("#edited_content").find("h1,h2,h3,h4,h5,h6");
    $.each(headings, function (i, heading) {
        attributes = heading.attributes
        $.each(attributes, function (j, value) {
            if (value.name == 'id') {
                alert("id present");
            } else {
                alert("id absent");
                $(this).attr('id', i);
            }
        });
    });

Upvotes: 0

Views: 422

Answers (2)

Arun P Johny
Arun P Johny

Reputation: 388406

Try a simple

var headings = $("#edited_content").find("h1,h2,h3,h4,h5,h6");
headings.attr('id', function(i, id){
    return id || 'prefix-' + i
})

Demo: Fiddle

If you want you can fine tune it using a not() filter like headings.not('[id]').attr(...)

Upvotes: 2

Milind Anantwar
Milind Anantwar

Reputation: 82241

try this:

   if ($(this).attr("id"))) {
         alert("id present");
    } else {
        alert("id absent");
        $(this).attr('id', i);
    }

Upvotes: 0

Related Questions