Adding anchor tags to HTML headers using CSS: a step-by-step guide

I have compiled some of my WordPress blog posts into a single HTML document to be published as a PDF using Prince. However, I am facing an issue with the table of contents: It links to documents outside of the HTML file using <a href="...">.
Question: Is there a way to insert anchors <a id="..."> using CSS directly into the HTML document? ("..." representing the title of the <h1> tag)

Answer №1

According to Joseph Webber, extracting the text ('foo') from <h1>foo</h1> without using JavaScript is a challenging task. However, creating a table of contents from selected WordPress blog posts can be achieved with the following JS script. It assumes a specific structure:

<div id="pagecontent">
    <ul>
        <li><a ...>1st Title</a></li>
        ... 
        <li><a ...>last Title</a><li> 
    </ul>
    ...
    <h1 ...>1st Title</h1>
    ...
    <h1 ...>last Title</h1>
</div> 
<script>
window.onload = function () {
    linesHTML = document.getElementById("pagecontent").innerHTML; /*get HTML-Text*/
    linesHTML = linesHTML.split('\n'); /*split into lines*/
    for (i=0;i<linesHTML.length;i++) { /* loop over the lines */
        posH = linesHTML[i].indexOf('<h1'); /*get position of <h1> header*/
        posA = linesHTML[i].indexOf('<a');  /*get position of <a> anchor*/
        if (posH > -1){ /*header found?*/
            linkText=getLinkText(linesHTML[i],'h1'); /*get the header text */
            linesHTML[i] = linesHTML[i].substring(0,posH+4) + 'id="' +linkText + '" ' + linesHTML[i].substring(posH+4); /*add the anchor as id with linkText as anchor*/
        } else if (posA > -1) { /*anchor found?*/
            linkText=getLinkText(linesHTML[i],'a'); /*get anchor from TOC*/
            linesHTML[i] = linesHTML[i].substring(0,posA+1) +'a href="#' + linkText + linesHTML[i].substring(linesHTML[i].indexOf('a">')+1); /*replace anchor with linkText*/
        };
    };
    document.getElementById("pagecontent").innerHTML=linesHTML.join('\n'); /*replace the doc with the all the lines*/
};
function getLinkText(line,htmlToken) { /*get the text of header/anchor*/
    linkText=line.substring(line.indexOf(htmlToken+'">')+htmlToken.length+2,line.indexOf('</'+htmlToken+'>'));
    linkText=linkText.replace(/[^A-z^0-9]/g,'-'); /*replace all non alphanum chars by '-'*/
    return linkText;
};
<script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Changing the hidden input value to the data-id of a selected <a> element

I've set up a form with a dropdown menu and subdropdowns, generated using a foreach loop through a @Model. When I click on one of the options, I want the value of my hidden input field to match the data-id of the clicked item. This is what I have in ...

issue with customized select dropdown within a bootstrap modal window

Exploring how to implement a customized select box with unique CSS and search functionality within a Bootstrap modal. Here is the code snippet for the select element: <link rel="stylesheet" href="chosen.css"> <select data-placeholder="Choose ...

Create an HTML page that allows for vertical scrolling even when there is no

After creating a basic html-page with only a navbar and footer using bootstrap, I noticed that the site has become scrollable. Why is this happening? Below is my Footer CSS: /* Sticky footer styles -------------------------------------------------- */ ht ...

A beginner's guide to retrieving random names and images from JSON data for every object using JavaScript

I have a creative idea for a random ruffling game, where it picks a user's name and image randomly. However, I'm facing an issue with ensuring that each image matches the correct user when selected randomly. I want to make sure that every objec ...

How can I prevent katex from overflowing?

Currently, I am facing a challenge in handling katex equations that overflow in a react native webview. I am attempting to dynamically break the equations into multiple lines to prevent scrolling and display them separately. Any assistance on this matter ...

Is it possible to create a webpage where the header and footer remain static, while the content in the body can be dynamically changed

I am in the process of creating a webpage where main.html will load a page with a static header and footer that remains unchanged when navigation links are clicked. I'd like to achieve this using Javascript, with the body content being sourced from an ...

Open the link and input the text into the text box?

Suppose I have the following JavaScript code: <script language="javascript" type="text/javascript"> function addText() { var newText = document.myForm.inputText.value; document.myForm.description.value += newText; } </script> I want t ...

The collapse button in Bootstrap 3.3 and jQuery 1.1 appears to be visible but unresponsive when clicked

This code isn't functioning properly as it displays the three horizontal bar button, but nothing happens when clicked. bootstrap-3.3 jquery-1.1 Toggle navigation CopyHere <div class="collap ...

Tips for making a Scroll Button

I am in the process of designing a horizontal website and I would like to incorporate two buttons, one on the left and one on the right, that allow users to scroll to the left and right, respectively. You can check out the site I am currently working on h ...

Is it possible to set the <li> background to full width and center it vertically?

Getting straight to the point: I have a vertical menu bar and I am looking to have an <li> element with a full background color and vertical alignment. I came across a suggestion to add vertical-align: middle;, but that doesn't seem to work wel ...

What could be causing my Bootstrap Carousel to malfunction?

Currently, I am developing a MEAN stack application with Angular 7. In this project, I have incorporated a Bootstrap Carousel, but unfortunately, it seems to be malfunctioning. #slider .item { height: 500px; } .carousel-caption { font-size: 18px; } ...

Looking to create cascading dropdown options

I am working on a form that includes 3 dropdowns with the same options listed below: <select id="one"> <option value="1">Select</option> <option value="1">One</option> <option value="2">Two</option> <option val ...

Unable to configure background image in web-page created with flask

I'm attempting to set a background image within an HTML document using the code below: <body style="background-image: url( {{url_for('static', filename='img/library2.jpg') }} )"> However, the image is not displaying. The ou ...

Applying drop cap styles to generated content in pseudo-elements

In my blogging Q&A section, I wanted to add a unique touch by starting each question with a large question mark and each answer with a large exclamation mark as a drop cap. I tried using the ::first-letter pseudo-element along with the initial-letter prope ...

What is causing the dysfunction of angular2 form when used with the HTML <form> tag?

Can someone explain the strange behavior of the <form> element in ng2 to me? I have noticed something odd and need some clarification :) To demonstrate, I have created a simple Plunker example at this link: https://plnkr.co/edit/vdrHJBNdd26y6YhPXTHD ...

Adding a class name to the three active, visible, and shown slides in SwiperJS is a simple process that can be done by

Currently, I am working on customizing a carousel in Swiper with slidesPerView={3}. My goal is to style the sliders that are not visible on the screen. I have made multiple attempts to achieve this: First, I tried adding the attribute slideActiveClass="sw ...

I'm having trouble getting the second controller to function properly in my AngularJS application

I've been looking everywhere for a solution on how to implement two controllers, but I can't seem to get it working. Could there be something wrong with my HTML or could the issue lie in my script? Here is the JavaScript code: <script> v ...

Using line breaks in JSX

In my application, I save all the text in a settings.ts file. However, I am facing an issue where \n does not seem to add line breaks as expected. Are there any alternative methods to include breaklines in my text? My tech stack includes Next.js, Reac ...

What causes the extra gap above an element even when there seems to be no margin or padding applied to it?

I can't seem to figure out why there is extra space above the elements in my nav bar. I've checked the margin and padding, but there is a large gap above my #logo and #searchbox that is causing layout issues. How can I remove the space above thes ...

Is it possible to automatically navigate to a different webpage upon clicking anywhere on the background?

I have created a website with a gif background and I want to redirect to another site (like softlaunch) after clicking anywhere on the screen. This is my HTML and CSS: body { background: url(main.gif) no-repeat center center fixed; -webkit-backgrou ...