How can i automatically generate anchor ids to h2 and h3 added using ck editor ? I need it for making a table of content.
-
1Not sure if anyone has built an integration module for this, but I would leverage ckeditor.com/cke4/addon/toc– KevinCommented Jul 8, 2020 at 13:12
-
interesting but would probably create a toc for each content type fields. A module would be needed to generate a toc for the full page , including paragraphs etc . I have maded it in JS– MatoeilCommented Jul 8, 2020 at 13:15
-
1I've been looking for a plugin that lets authors assign/change ID attributes to any selected element via the UI; it would extend this nicely. CKE4 doesn't have it, but @rhystubbs created a plugin to do this in CKE5: github.com/ckeditor/ckeditor5/issues/7369– TimmahCommented Jul 11, 2022 at 7:46
Add a comment
|
1 Answer
in JS, id set from the h2 label two first words :
const headings = document.querySelectorAll(
".article--full h2, .article--full h3"
);
const tocElements = createTocElementsArray(headings);
function createTocElementsArray(headings) {
const tocElements = [];
for (const item of headings) {
if (item.id === "") {
item.id = item.firstChild.data
.split(" ")
.slice(0, 2)
.join("-");
}
....
}
-
1There's a safer example of this method on SO that checks if the ID exists before assigning it: stackoverflow.com/questions/12257668/…– TimmahCommented Jul 11, 2022 at 7:48