Break up a list into separate paragraphs and style each word using individual CSS

I have a user-generated paragraph that consists of a list of words separated by commas, such as "dog, cat, hamster, turtle." I want to be able to individually assign attributes to each word in the list.

Check out this image for reference

In the example image provided, instead of having a shared border and color for all words in the list, I would like to give each word its own distinct border and spacing between them. Is this something that can be achieved?

Answer №1

Check out this method for achieving the desired outcome (but remember to attempt solving it independently next time):

VIEW DEMO

If your HTML looks like this:

<div id="sample">apple, banana, orange</div>

Your JavaScript code should be:

function separateItems() {
    var element = document.getElementById("sample");
    var itemsArray = element.innerHTML.split(", ");
    
    element.innerHTML = "";
    for (var j = 0; j < itemsArray.length; j++) {
        var newSpan = document.createElement("span");
        var itemValue = itemsArray[j].trim();
            newSpan.innerHTML = itemValue;
            element.appendChild(newSpan);
    }
}

separateItems();

CSS styling:

#sample span { padding: 4px 6px; background-color: #f0f0f0; margin: 0 8px; border-radius: 5px;}
  • Feel free to ask any questions or provide feedback on this approach. Best of luck!

Answer №2

Hey there Henrik! If you're looking to style a specific word with some special CSS, you can do that by using the span tag like:

<span class="highlight">Highlighted Text</span>

Then in your CSS file, you would add:

.highlight{color: yellow;}

If you want to add a border as well, you can create another class like

.border-highlight{border: 2px solid yellow;}

It may get a bit more complex if the content is generated dynamically, but it's definitely achievable. Hope this solution works for you!

Answer №3

Ahhh, the trick is to use Indexof to separate each word and then apply unique CSS to them individually.

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

The HTML source code in the browser varies from the output obtained through Python requests

I've noticed a discrepancy between the HTML source code displayed in my browser and the code I receive when using Python's requests.get function. You can see the image depicting this issue at the following link: Any thoughts on why this might be ...

"Utilizing FileReader to seamlessly integrate data into FormData without the risk

Currently, I'm in the process of constructing an ajax file uploader. This is made possible thanks to the recently introduced FormData interface. Everything seems to work as expected when using the original file. However, I encounter issues when conver ...

The hyperlink does not display any text indicating an issue in the Wave accessibility evaluation tool

On my HTML page, there is a certain code snippet: <a href="example.com"><i class="myclass"></i></a> <a href="http://www.google.com" class="cart visible-xs"><i class="t-icon t-icon-cart-xs-2"></i></a> Des ...

Aligning table data elements within a division

Currently working on revamping a tech night website for my school. I made some changes to the navbar, switching it from the side to the top. However, I'm struggling to get the table data and menu to center properly within the div. If you'd like ...

The issue with adjusting the top position in jQuery

As I continued scrolling on my page, I encountered an issue with adjusting the top offset using jQuery on my element. I want the element with id goToLog to become fixed on the page after scrolling 80px. This functionality is working correctly. However, wh ...

Use `$$state: {…}` within the request rather than the data

When attempting to send a request with data, I am only getting "f {$$state: {…}}" in the console. $scope.createTask = function () { var req = $http.post('api/insert', { title: $scope.newTitle, description: ...

Error encountered while adding x-ray-scraper to project using Npm

I am currently working on a Vue application and utilizing the x-ray-scraper library. However, when I attempt to run npm run serve in the terminal to preview the application locally, I encounter the following error: This dependency was not found: * _http_c ...

Exploring different ways to customize the grid style in Angular 6

Here is the style I am working with: .main-panel{ height: 100%; display: grid; grid-template-rows: 4rem auto; grid-template-columns: 14rem auto; grid-template-areas: 'header header''sidebar body'; } I want to know how to cha ...

Display DIV when the page loads, and hide it when any radio button is clicked

If you're looking to create a page with hidden content that is revealed when specific radio buttons are clicked, you've come to the right place. The concept is simple - the page starts off blank, but upon selecting a radio button, one div is show ...

ShadowBox replacement for IE8

After much experimentation, I am on the verge of achieving an inset box shadow for IE8 without relying on JavaScript. Take a look at the screenshot below: Since Internet Explorer versions 5.5 through 8 only support Microsoft's "dropshadows" and "sha ...

What is the reason for a type narrowing check on a class property failing when it is assigned to an aliased variable?

Is there a way to restrict the type of property of a class in an aliased conditional expression? Short: I am trying to perform a type narrowing check within a class method, like this._end === null && this._head === null, but I need to assign the r ...

I found myself pondering the method to achieve the slightly blue tinted box that sits behind the image

Can you assist me in achieving this specific look? I have my MUI app bar and home page set up, but I'm unsure how to create the blue-ish box behind the image. Should I place the container within my app bar or integrate it into my homepage file? Additi ...

Tips for creating JSON using AngularJs to store tabular information

I successfully created an HTML page using AngularJS. <form name="target" ng-submit="createAllKeywordsJSON(codeMasterList)"><!-- createAllKeywordsJSON() --> <input type="submit" value="Save" class="myButton" name="submit" style="margin: ...

Guide on displaying the AJAX response in CakePHP 3.1

I'm working with a table that contains checkboxes. After selecting them, I want to calculate the sum of values from the table in a modal before confirming the form submission. Can someone guide me on how to render the AJAX response from the controller ...

Removing an event from Fullcalendar

With the help of a post on StackOverflow, I managed to modify my select: method to prevent users from adding an event on a date before NOW. However, there is a drawback. When a user clicks on an empty time slot and the system displays an alert message, th ...

Adjust the content within an HTML div by utilizing AngularJS

Snippet of AngularJs code to display different content based on selection: <select> <option value="0">--Select--</option> <option value="1">Individual</option> <option value="2"> ...

Create a regular expression that permits a sequence of numbers (either integer or decimal) arranged in groups of up to five, with each

Is it possible to create a regular expression that allows integers and decimals? var reg = /^((\s*)|([0-9]\d{0,9}(\.\d{1,3})?%?$))$/.; How can users input 0 to 5 groups of integers and decimals separated by |? Updated: This regex sh ...

Issues with CSS filters affecting the layout of webpage elements

Is there a way to keep a div pinned to the bottom of the viewport while applying a filter to the body in CSS? I tried using position: fixed; bottom: 0px, but it seems to mess up the positioning when a filter is added to the body. body { filter: bright ...

Utilize Flexbox to arrange elements in a column direction without relying on the position property in CSS

Flexbox - align element to the right using flex-direction: column; without relying on position in CSS Hello everyone, I am looking to move my row element to the right without using positioning. This code includes flex-direction: column; and I do not have ...

The error being thrown is related to Next.js 13 cache setting of 'no-store'

Check out this snippet of code async function fetchData() { const response = await fetch('http://127.0.0.1:1337/api/posts', { method: 'GET', headers: { 'Content-Type': 'application/json', Author ...