A method for generating CSS code from the structure of an HTML document

I am currently working on developing a recursive function that takes an HTML document tree and generates formatted CSS using only child operators (>), but I seem to be stuck. If you could provide some hints or ideas, I would greatly appreciate it.

The main concept is to transform something like this:

                  body
               /       \
             div        div
            /   \    /   \  \
           h1   p   p    ul  div
                        / \
                       li  li 

into:

div
    div > h1
    div > p
    div > p
    div > ul
        div > ul > li
        div > ul > li
    div > div

Alternatively, in string format:

"div\n\t div > h1\n\tdiv > p\n\tdiv > p\n\tdiv > ul\n\t\tdiv > ul > li\n\t\tdiv > ul > li\n\tdiv > div"

I already have a method for retrieving the 'body' and its corresponding tree structure. The necessary functions are part of an object named XMLNode:

  1. getChildNode(int k): returns the XMLNode object representing the kth child. Returns a special object if none exists.
  2. isEmpty().
  3. getName(): retrieves the node name as a string-like object that can be converted into a string.

My current approach involves calling:

std::cout << tree2CSS(bodyNode);

where the tree2CSS function is defined as follows:

std::string tree2CSS(XMLNode & rootNode, unsigned depth = 0)
{
    int i = 1;
    XMLNode childNode = rootNode.getChildNode(i);
    std::string accumCSS;
    while (!childNode.isEmpty())
    {
        std::string tabs(depth, '\t');
        accumCSS.append("\n" + tabs);
        if (depth > 0) accumCSS.append(" > ");
        accumCSS.append((std::string)childNode.getName() + tree2CSS(childNode, depth + 1));
        childNode = rootNode.getChildNode(++i);
    }
    return accumCSS;
}

Unfortunately, this implementation seems to be failing, and I cannot pinpoint the issue. Any assistance would be greatly appreciated.

Answer №1

If you're looking to display the complete ancestry information for each item, it's important to keep track of all parents, not just the depth.

One approach could be handling the printing outside the loop and using the loop solely to traverse through the children.

Consider this alternative code snippet:

std::string tree2CSS_(XMLNode& rootNode, std::vector<std::string>& pred)
{
    std::string accumCSS(pred.size(), '\t');
    std::string name = rootNode.getName();

    for (size_t i = 0; i < pred.size(); ++i) {
        accumCSS += pred[i] + " > ";
    }
    accumCSS += name + "\n";

    size_t i = 0;
    XMLNode& childNode = rootNode.getChildNode(i);

    pred.push_back(name);
    while (!childNode.isEmpty()) {
        accumCSS.append(tree2CSS_(childNode, pred));
        childNode = rootNode.getChildNode(++i);
    }
    pred.pop_back();

    return accumCSS;
}

std::string tree2CSS(XMLNode& rootNode)
{ 
    std::vector<std::string> pred;
    return tree2CSS_(rootNode, pred);
}

In this version, a vector of preceding strings is used to store the ancestor nodes, with its size representing the recursion depth. The code is split into two parts: a front-end function providing the vector and the recursive implementation.

This implementation includes both the parent node and prefixes it to all CSS statements. To exclude the top-most node, iterate over the children of the parent node within the front-end function.

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

Filling a table cell with a div that spans 100% height

I am currently working with Bootstrap and I am attempting to create three columns filled with text overlaying a rectangle. The squares within the columns should have equal height and there needs to be spacing between them. Through the use of display:table ...

Utilizing JavaScript to present JSON data in HTML tables across various sections of a website

Utilizing JScript to retrieve data from a JSON API URL, I have incorporated the data in the JSON file displayed below - containing information on 8 horse races with details like Horse number, Horse name, and their odds. My goal is to create a Jscript code ...

Escaping from its container, text breaks free with the power of CSS

Experiencing difficulties with CSS flex layout that are proving challenging to resolve. HTML: <div class="image-view"> <div class="info"> <span class="label title">d37ci4x.jpg</span> <span class="label scale ...

How can I remove the popover parents when clicking the confirm button using jQuery?

I am having trouble sending an AJAX request and removing the parent of a popover after the request is successful. I can't seem to access the parent of the popover in order to remove it, which is causing me some frustration. // Code for deleting w ...

CSS footer element refuses to disappear

This sample application features a header, footer, and a content div that includes a table displaying various statistics of basketball players. One issue I encountered was with the footer when there were many entries in the table. This caused the footer t ...

The Surprising Results of using std::move with Pointers of Type T in C++

In the following code snippet, I define a variable called pval which is attempting to derive T&& from a T* [where T is an int]. According to the type information [decoded using abi], the derived type is int*. However, when comparing the int* type ...

The CSS file I've linked to in my HTML (ejs) document seems to be getting

As I work on developing my app from the backend, I am encountering an issue with loading CSS locally on my page. I am utilizing Node.js, Express.js, and EJS for my pages - part of the MEN/MEAN stack. <link href="../public/stylesheets/style.css" rel="st ...

Tips for bypassing the Windows tree command

C:\Users\client>npm install -g tree-cli + <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c7b3b5a2a2eaa4abae87f7e9f1e9f3">[email protected]</a> updated 1 package in 2.374s C:\Users\client& ...

What is the best way to extract the src attribute from an image tag nested within innerHtml?

In the developer tools, navigate to console and enter: var x= document.getElementsByClassName('ad-area')[0].innerHTML; x returns: '<a href="/members/spotlight/311"><img class="block-banner" src="https://tes ...

CSS styling for a background image in the header

Why isn't my background image showing up even though I've used a direct link to the image? What could be causing this issue? .header { background-image: url("https://www.africa.com/wp-content/uploads/2015/07/Kenya.jpg"); background-attac ...

Align an image in the middle with a heading

I am currently working on aligning a picture and heading in a header section. My goal is to center both elements, with the picture being twice as tall as the heading. So far, I have them stacked one above the other: .body { font: 15px/1.5 Arial, Helveti ...

Issue with div:after transition not functioning in Safari

The transition effect on div:after does not function properly in Safari. Below is the code for reference: HTML: .bbtn { width: 151px; height: 48px; background: #ef2e41; margin: auto; margin-top: 32px; -webkit-transition: all 0.3s ease-in-ou ...

Toggle the disable state of a button depending on a specific condition

I have a scenario where I am fetching data from a server, and I need to apply a filter to a specific column. The requirement is that if the "bought" column (boolean) has a value of true, then the edit button should be disabled; otherwise, it should be enab ...

Guidelines for pinpointing local directories

Recently, I obtained a source code for a website navigation that includes a unique set of icons known as "Typicon." The HTML in the source code contains the following: <link rel="stylesheet" type="text/css" href="css/component.css" /> Within the C ...

Concealing the value of 'Zero' in an input field with TypeScript and Angular 2

<input type="text" class="form-control" id="transactionAmount" maxlength="10" HideZero="true" [(ngModel)]="userBalance.transactionAmount" ...

Is there a way to change the default output path of the test report created by CTest?

Is there a way to change the default path for the test report generated by CTest from Testing/Temporary? I have been unable to find any solution to modify this path. Does anyone have any suggestions? I am interested in manually setting the test report pat ...

Using Python to manipulate byte arrays for serial communication

I have a program that needs to send a byte array using serial communication, but I am not sure how to do this in Python. I found a function in C/C++/Java that creates the necessary byte array: byte[] floatArrayToByteArray(float[] input) { int len = 4*in ...

Adjust the size of iCheck jQuery radio buttons

I have implemented the iCheck Plugin for radio buttons in Angular Directive, but I am facing an issue with resizing the radio button to a smaller size. Does anyone have any suggestions or solutions for this? ...

Is there a way to create a marker that changes color when hovering over the text directly below it?

Hi everyone, I hope you're all doing well. Currently, if you hover over the marker, it changes color. However, I want this effect to apply when hovering over the text below as well. Is there a way to create a connection between these two div elements? ...

Change the type of button in the Jquery UI dialog form to be submit

I'm struggling with my Ui dialog form using jquery. The Submit and Cancel buttons are currently set to type="button", but I want to change the type of the submit button to "submit". Does anyone know how I can achieve this? I've tried multiple ti ...