Formatting specific elements within an array

I am working with an array of names, some of which are repeated. These names are then split in half and displayed as li. One thing I am struggling to figure out is how to style the name Joeyc with text-decoration: line-through; on all instances of .book where joeyc is present. Check out my code snippet below along with a link to a JSFiddle:

 <div id="book1" class="book">
       <ul class="hardcover_front">
        <li></li>
        <li></li>
      </ul>
       <ul class="hardcover_back">
        <li></li>
        <li></li>
      </ul>
       <ul class="book_spine">
      </ul>
     </div>
    .
    .(similar blocks for book2-book10)
    .

<script>
var votenames = ["Joeyc", "JakeP97", "Joeyc", "TheKid", "Joeyc", "TheKid", "Joeyc", "JakeP97", "ExploreMeDora", "Alvaro"];
var ballots = ["#book1", "#book2", "#book3", "#book4", "#book5", "#book6", "#book7", "#book8", "#book9", "#book10"];

function splitName(plName,ballotNum) {
    var halfplName = Math.round(plName.length / 2);
    var firstplName = plName.substr(0, halfplName);
    var lastplName = plName.substr(halfplName, plName.length);
    $(ballotNum + ' ul.hardcover_front').find('li:nth-child(2)').html(firstplName);
    $(ballotNum + ' ul.hardcover_back').find('li:nth-child(1)').html(lastplName);
}

for (i=0; i<ballots.length; i++) {
    splitName(votenames[i],ballots[i]);
}
</script> 

Here's the link to the JSFiddle.

Answer №1

While CSS selectors are unable to target elements based on their content, jQuery selectors offer a solution for this limitation:

$('li:contains("two")').css("text-decoration", "line-through");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<li>one</li>
<li>two</li>

However, an alternative approach might be to dynamically generate the HTML code using your script. This way, you can easily apply CSS styles or classes to specific elements based on the corresponding array item.

Answer №2

If you want to find a specific <li> element based on a certain condition, you can use an if statement to search for it.

Once you have located the desired element, you can apply a CSS class using the following code snippet:

document.querySelector("#myelement").classList.add("myclass");

This will allow you to add your preferred style to the element.

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

Retrieve the user-inputted data from an Electron BrowserView's input field

Consider this scenario where a BrowserWindow is set up with specific security settings, including enabling the webviewTag: true for project requirements. let webPrefs = { plugins: false, nodeIntegration: false, nodeIntegrationInWorker: false, ...

How to properly read a multipartform-data stream in NodeJS

I am attempting to handle a multipartform-data stream that may consist of various files and fields, in order to save the files to a directory on a uWebsockets.js server. Below is the code I am using: let boundary = null; let fields = []; let st ...

I am looking to create a split div with a diagonal line running through

Is there a way I can create this Mockup using html5 and css3, but also add diagonal lines to divide the div? Any suggestions on how to achieve this? ...

Zurb Foundation gem causing navigation errors

Typically, I rely on the Twitter Bootstrap Rails gem for my projects, but this time I decided to try out the Zurb Foundation gem. Following the installation instructions meticulously, I added the navigation code: <div class="row"> <div class="th ...

Vue - a guide on customizing a prop in a parent component

I have implemented a wrapper component that encapsulates a Quasar q-select element in the following manner: <template lang="pug"> q-select( :options="organisations" option-value="id" v-bind="$attrs&quo ...

Encountering a runtime error in React while making an async call on a NextJS 13 page

I am currently working on implementing async calls using the new app layout in NextJS 13. I have been referring to the latest documentation page. However, I have encountered an error that I can't seem to resolve. Below is a snippet from my app/page.t ...

Material Design Autocomplete search feature in Angular 2

I'm encountering some challenges with autocomplete in Angular2 Material Design. Here are the issues I'm facing: 1. When I type a character that matches what I'm searching for, it doesn't display in the autocomplete dropdown as shown in ...

Achieve a full page layout with content and attach the footer to the bottom using flexbox in Tailwindcss and Nextjs

How can I use flex-grow to make the body section fill the screen and keep the nav fixed at the bottom? I'm having trouble figuring out which elements to apply these properties to. Can anyone provide guidance on which element should have these styles? ...

Vue 3 - Using Emit Functionality in a Reusable and Composable File

I'm trying to utilize the emit function in my file called useGoo.ts import Swal from "sweetalert2/dist/sweetalert2.js"; export default function useModal() { const { emit } = getCurrentInstance(); function myId() { emit('id&ap ...

Updating a jQuery div issue

Hey there, I apologize for bothering you again, but I'm facing another issue with jQuery. It's the same code. $('.tab').click(function() { $(this).unbind("click"); var classy = $(this).attr("class").split(" ").splice(- ...

Utilizing Sequelize with Typescript for referential integrity constraints

After defining these two Sequelize models: export class Users extends Model<Users> { @HasMany(() => UserRoles) @Column({ primaryKey: true, allowNull: false, unique: true }) UserId: string; @Column({ allowNull: false, unique: tru ...

How come the hidden container does not reappear after I click on it?

I'm having an issue with a hidden container that holds comments. Inside the container, there is a <div> element with a <p> tag that says "Show all comments". When I click on this element, it successfully displays the comments. However, cli ...

Adding a CSS style to specific sections of a string that is quoted in a Razor ASP.NET file

Is it possible to format a specific part of a string? I'm trying to only stylize the word within quotation marks. This is my cshtml code: { <div class="h-44 overflow-auto text-left mx-4 mb-4"> <p ...

Displaying various charts in a single view without the need for scrolling in HTML

How can I display the first chart larger and all subsequent charts together in one window without requiring scrolling? This will eventually be viewed on a larger screen where everything will fit perfectly. Any recommendations on how to achieve this? Here ...

Displaying only the validation messages that are accurate according to the Vuetify rules

<v-text-field label='New Password' class="required" v-model='password' type='password' :rules="passwordRules" required> </v-text-field> passwordRules: [ value => !!value || 'Pl ...

What is the reason behind text underline being disabled when using "hidden: overflow" in CSS?

I have a long text string that I want to auto-shorten using CSS with text-overflow: ellipsis, but it's removing the underline from my link. Here is the code: NORMAL .link { font-weight: bold; cursor: pointer; color: black; text-decorat ...

What is the best way to dynamically adjust the size of a Google map on my website automatically

I need assistance with placing a Google map on a webpage along with textboxes in the div below it: <div id="map_area"> <div id="map_canvas"></div> </div> <div id="date_range"> <input type="text" id= ...

Different ways to save data fetched from a fetch request

I'm fairly new to React and could use some assistance. I am trying to retrieve data from a movie database based on a search term. I have a method called getMovies where I utilize fetch to grab the data. The information is located in data.Search, but I ...

How to disable CSS transition on Angular 4 component initialization

I am facing a major issue with css transitions and Angular 4. The problem arises when using an external library that includes an input counter feature. Despite knowing that no additional styling is being applied to the wrapped input, the application has a ...

Warning: UnsupportedRepoVersionError: The repository versions are not compatible. Please check the version of IPFS-JS (0.55.3) and Node.js (14.17.0) being used

Recently, I delved into the world of ipfs js and currently have version 0.55.3 installed (https://www.npmjs.com/package/ipfs). Alongside, my setup includes node js version 14.17.0 (LTS) on MacOS BigSur 11.4. However, while following a tutorial at https:// ...