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
});