Creating visual aesthetics for code generated by JavaScript

I have implemented a JavaScript function that performs a "find and replace" operation, changing all the backticks in the HTML to <code> tags, and replacing all the pound signs with </code> tags. However, I am encountering an issue where my styles are not being applied unless I manually add them in the JavaScript file using the .css() method.

The desired outcome is to display the content between backticks and pound signs as block-level <code> elements (the <code> tags are dynamically generated from JavaScript) with a light gray background. Despite setting these styles, they are not reflecting on the page.

If anyone can provide assistance, it would be greatly appreciated.

This is the structure of my html file test.html:

<!DOCTYPE html>
<head>
<title>Script Test</title>
<script src="http://code.jquery.com/jquery-2.1.1.js"></script>
<link rel="stylesheet" href="styles/code/style.css" type="text/css">
</head>
<body>
<p>This is some code:
    `var p = 10; #  
    `var a = 5; #   
    `var x; #   
    `x = a * p; #    
    `console.log(x); #
    All I want is for this to work!
</p>
<script src="codeStyle.js"></script>
</body>

Here is the CSS code (compiled from SASS) in my style.css file:

body {
  color: #121212;
  font-family: 'Helvetica Neue', serif;
  font-weight: 300;
  letter-spacing: .25px; }

  body div.container {
    padding: 10px; }

    body div.container code.styled {
      font-family: arial, serif;
      background-color: #f9f9f9; /* soft gray bg color */
      display: block; /* block display style */
      margin: 2px 0 2px 2.5%;
      padding: 3px;
      width: auto;
      background-color: #fafafa;
      border: 1px solid #f5f5f5; }

 /*# sourceMappingURL=style.css.map */

Additionally, the JavaScript file codeStyle.js looks like this:

$('p').each(function() {
var text = $(this).html(); // Grab HTML from each <p>
text = text.replace(/`/gi,"<code class='styled'>"); // Replaces every ` with <code>
text = text.replace(/#/gi,"</code>"); // Replaces every # with </code>
$(this).html(text); // Set <p> html as replaced code
});

Answer №1

Partick's response highlights the issue with your CSS code targeting a non-existent element.

The problematic CSS snippet is as follows:

 body div.container code.styled { }

This selector does not match any content since there is no <div class="container">

To resolve this issue, you can either eliminate the problematic selector from the CSS:

body code.styled {}

or include the necessary selector in your HTML:

<div class="container">
    <p>Some text <code class="styled">some code</code>.</p>
</div>

Check out this Fiddle for a working example.

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

How can I prevent CSS styles from affecting all the tables on my website?

One issue I'm facing is that the CSS code intended for one table is affecting all the other tables on my website. Here is an example of the CSS code: tr:last-child td:last-child { border-bottom-right-radius:3px; } /*effects map*/ td { background: ...

What is the process for establishing a key on the request header to authenticate in Node.js?

I am a novice in the world of nodejs. My current project involves creating a basic server that writes JSON data to a CSV file. However, I have encountered a stumbling block: For authentication purposes, the request header must include an “appKey” para ...

Beginner with jQuery: Ways to isolate non-click functions in ajax content?

As a beginner in jQuery, I am facing a scenario where I am using jQuery .load() to load content into tabs on my page template. The issue is that the functions do not work unless they are directly placed within the content pages rather than an external Java ...

Accessing the form element in the HTML outside of the form tag in Angular 2

I am attempting to achieve the following: <span *ngIf="heroForm?.dirty"> FOO </span> <form *ngIf="active" (ngSubmit)="onSubmit()" #heroForm="ngForm"> <div class="form-group"> <label for="name">Name</label& ...

Is there a way to streamline the process of dragging and dropping multiple files with C# selenium automation?

I have successfully implemented code to drag and drop a single image, but I am unsure about the necessary changes needed to support multiple file uploads. Can anyone provide assistance with this? Thank you. driver.Url = "http://example.com"; IWebEleme ...

Guide on saving a Canvas element as a png file using php and ajax

I am trying to save an HTML canvas element as an image using PHP and jQuery AJAX. Below is the code I have written for the ajax request: var front_image = canvas.toDataURL('image/png'); //front image is a base_64 string $.aja ...

What is the best way to ensure that the text within Span children is properly laid out to match the width of the parent div tag?

This particular instance involves setting the width of the div tag to 200px and organizing all the span children to occupy the entire width of the parent div tag. If the first row is filled, the span tags should then flow into a second row. My attempt at ...

What makes CSS Overflow: hidden toggle from working initially to suddenly not working?

There seems to be an issue with the code below - it works fine initially, but as soon as I tweak the height values for .Image, it stops functioning as expected. The test image starts overflowing instead of staying hidden, and no matter how many times I a ...

Struggling to place the sans-serif font right at the edge of the H1 tag

Encountering a strange issue that suggests I might be overlooking something simple. Any thoughts on the following: I have a heading tag styled with a sans-serif font (loaded from Google fonts) and when I apply a background-color, the text does not align t ...

When the click event is triggered, insert HTML content into a div, clear any existing selection from the div, and

Looking to develop a biscuit selector feature that enables users to email their chosen biscuits. I require an on click event that adds the selected biscuit (image) to the biscuit barrel (basket). It should also allow users to remove any biscuits from the ...

The bytea data retrieved from Postgres does not match the original data I inserted

I have successfully integrated a React front end with a PostgreSQL back end using Express. I encountered an issue when handling byte arrays (Uint8Array) for files uploaded from the front end into the database. The file, which is 779 bytes in size, gets sto ...

Challenge with JavaScript personalized library

No matter how many times I review my code, I find myself perplexed. Despite my efforts to create a custom library of functions from scratch (shoutout to stackoverflow for guiding me on that), the results are leaving me puzzled. A javascript file is suppose ...

Using JavaScript to iterate through user input and generate an array of objects

I am attempting to iterate over input elements inside a div in order to generate an array of objects. <div id="time"> <input type="text" name="from" placeholder="12:00 AM" /> <input type="text" name="to" placeholder="12:30 AM" /> & ...

Is it possible to bind a function to data in Vue js?

Can a function be data bound in Vue? In my template, I am trying something like this: <title> {{nameofFunction()}}</title> However, when I run it, it simply displays 'native function' on the page. Any insights would be appreciated ...

Unable to access controller using jquery/ajax in CodeIgniter along with a bootstrap template

When loading a page into another, everything seems to be working fine except for the controller loading: https://i.sstatic.net/WpO4B.png The scripts and CSS are being loaded in the default page code, which might be causing the issue. The error message "Fa ...

What is the best way to detect and handle the destroy event in Kendo UI grids when a click event

How can I trigger a function when the delete button in a grid is clicked using JavaScript? ...

Is it possible to add or remove a class at the top of a div

Is there a way to create a fading effect for a class based on when a specific div enters the window? I am looking to implement this functionality, how can I achieve this? $(window).scroll(function() { var registerTop = $('.register').offset ...

Align several labels and text areas in the center

I am facing an issue with aligning multiple labels and textareas together. Currently, they line up like this: __________________ | | | | Label:|__________________| However, I want them to appear as fol ...

Troubleshooting ASP.NET MVC5: Partial view not loading dynamic JavaScript reference

In an effort to update a partial View containing an interactive world map, my objective is to refresh it with new data. I have a Controller action public JavaScriptResult DynMap(int id, List<int> relevantCountries = null){} This action returns the ...

What could be causing the Javascript Dynamic HTML5 Table to not display on the page?

I have a program that calculates the total price of products based on a specified quantity and updates an HTML table with these values. To demonstrate this, I am constantly taking input using an infinite loop. <!DOCTYPE html> <html> ...