Implementing JavaScript to add elements to class

Is there a way to use JavaScript to dynamically add classes to elements?

<div class="col-md-4 col-xs-6 work-item web-design" id="SetCategory">
.
.
<script>
        document.getElementById("SetCategory").classList.add('{{ $category->name }}');
</script>
.
.
</div> <!-- end work-item -->

I am having issues getting the <script> to function properly on my page.

P.S. Variable $category->name corresponds to categories such as food, shop, travel, hotel, and route. These categories determine the display when a button is clicked.

Answer №1

It appears that the task at hand is related to a college or university assignment, and it is important to note that Stack Overflow is not a platform for facilitating academic dishonesty. Seeking help on this website should always be done with proper citation.

The issue with your code is as follows:

document.getElementById("SetCategory").classList.add({{ $category->name }}' ')

This snippet is not valid in JavaScript and does not adhere to correct C syntax.

Here are a couple of steps to troubleshoot:

1) Familiarize yourself with using the web browser's inspector tool (Console Tab) in Chrome, Firefox, Edge, and IE 11 by pressing F12. This will display an error message like

Uncaught SyntaxError: Unexpected token {
in the console output.

2) For JavaScript documentation, the MDN web docs are a valuable resource. You can refer to the classList section here: https://developer.mozilla.org/en-US/docs/Web/API/Element/classList. Specifically, check out line 9 of the first code example on that page, which looks like this:

const div = document.createElement('div');
div.className = 'foo';

// Initial state: <div class="foo"></div>
console.log(div.outerHTML);

// Using the classList API to manipulate classes
div.classList.remove("foo");
div.classList.add("anotherclass");

// Result: <div class="anotherclass"></div>
console.log(div.outerHTML);

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

Is there a way to align both the horizontal and rotated lines to intersect at a common point in HTML and CSS?

As a beginner, I'm looking to create a structure resembling a thigh, leg, and ankle using thick lines. My aim is to rotate them with animation, ensuring that the joints between the lines mimic those of a knee joint and hip joint. Below is the code sn ...

Creating a layered image by drawing a shape over a photo in Ionic using canvas

While there are plenty of examples demonstrating how to draw on a canvas, my specific problem involves loading a photo into memory, adding a shape to exact coordinates over the photo, and then drawing/scaling the photo onto a canvas. I'm unsure of whe ...

Exploring the process of defining and authenticating an array of objects utilizing cuid as the key and ensuring the object contains designated properties

I have a customized data set that requires validation: { "name": "Some unique name", "blocks": [ {"cj5458hyl0001zss42td3waww": { "quantity": 9, "rate": 356.77, ...

Positioning pictures in front of a backdrop

I'm facing an issue with a section that slides into view with a blue background. I want to add a picture in the upper left corner, but it's barely visible and the blue background disappears. Here's a snippet of the HTML code: <header id ...

Focusing on the initial element following CSS prioritization

Check out this codepen link: http://codepen.io/muji/pen/XpEYzO I am looking to target the first element after it has been sorted using a CSS "order" property and apply another CSS property to it. Is there a way to use jQuery or any other method to identi ...

Applying the Directive/Isolated Scope as Embedded HTML within an Angular-Bootstrap Popover

If you're using the angular-ui popover, you have the ability to include HTML content within it. However, I encountered some difficulties in placing a directive called sampleDirective inside the popover. Despite my attempts with the $sce.trustAsHtml an ...

How can the Node app utilize an HTML page to reference another JavaScript file? Ran into an unexpected syntax error: `Uncaught SyntaxError: Unexpected token '<

I'm trying to figure out how to call another script from an HTML page that is being served by my node project's localhost server. Here's the basic setup: index.js var http = require('http'); var fileSystem = require('fs' ...

Creating a clickable navigation menu item with a clickable caret located on the same line

I've been developing a solution using Twitter Bootstrap to create a main navigation menu that expands upon hover on desktop, while the menu expands when clicking the caret on mobile (caret hidden on desktop). Additionally, I aimed to make the top-leve ...

Remove the float from the final list item in order to resolve display issues in Internet Explorer

I am trying to create a menu with the following HTML structure: <ul> <li id="btnHome"><a href="#">Link One</a></li> <li id="btnAbout"><a href="#">Link Two</a></li> <li id="btnContact"> ...

.submit fails to function when the bound object has been updated via an ajax call

I managed to implement an AJAX commenting system where, upon clicking the Post Comment button, an ajax call is made instead of submitting the form traditionally. Everything was working smoothly until I tried refreshing the page with the comment submit butt ...

Creating a virtual URL version for the Ultraviolet App express server in response to a client's access

Ultraviolet App is an innovative library that leverages Ultraviolet technology to bypass various service restrictions. My goal is to utilize it for a specific task: The requirement involves a list of services, where clicking on one triggers a request to t ...

Server Error: Experiencing an overload of renders. React has set limits on the number of renders to avoid getting caught in an endless loop

I am currently attempting to develop a basic stopwatch application and encountering the following error message. Despite trying various solutions from similar queries, I have not been able to pinpoint the root cause of this issue or resolve it. Below is t ...

What is the reason for jQuery selector variables not functioning within namespaces?

I'm struggling to figure out why my code isn't working as intended. I'm trying to declare multiple variables, but something seems to be off. Can anyone help me spot the mistake? var message = (function ($) { var $modalBody = $( ...

What methods are available to modify HTML content using Node.js?

I am looking to modify the contents of my HTML file (index.html) below: <html> <body> <div id="greeting">Hello world</div> </body> </html> I want to change this using Node.js in the backend. Below is the Node.js cod ...

What steps can be taken to avoid an abundance of JS event handlers in React?

Issue A problem arises when an application needs to determine the inner size of the window. The recommended React pattern involves registering an event listener using a one-time effect hook. Despite appearing to add the event listener only once, multiple ...

Bootstrap 4 Row failing to fill entire div width

I am currently designing a bootstrap 4 layout with four columns, but starting with just three. I have an outer div container and an inner row with three columns. However, when I add borders to all the containers, I notice that the row does not expand to fi ...

Tips for maintaining the footer at the bottom of the page regardless of the screen size

In my current project, I am dealing with several web pages. For each page, I have arranged three div tags: Header Body (content) Footer The issue arises when it comes to the body div tag, which houses the main content of a page such as forms and descrip ...

Heroku is incompatible with deploying MERN applications

I've been working on deploying my React app through NodeJS and Heroku, but I keep encountering an issue in the browser. Uncaught SyntaxError: Unexpected token '<' Resulting in a blank white page being displayed. I've tried sever ...

Obtain a string in JSON format upon clicking in Angular 2

I am working on extracting the title from a json response using a click event. Currently, I can retrieve all the titles when the button is clicked, but I am looking for a way to obtain a specific title based on the button or a href that the user has clicke ...

Best Practices for Managing Asynchronous Updates in Angular Controllers

Let me explain my current setup -- I have a controller that utilizes a service to perform some tasks and then fetches data asynchronously. Right now, the data is returned after a timeout, but ideally it would involve more complex operations: This is how m ...