Reputation: 75
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
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
Reputation: 82241
try this:
if ($(this).attr("id"))) {
alert("id present");
} else {
alert("id absent");
$(this).attr('id', i);
}
Upvotes: 0