简体   繁体   中英

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);
            }
        });
    });

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(...)

try this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM