Apply multiple CSS properties to elements by extracting the innerHTML

I am currently trying to apply some CSS to certain div elements on my webpage.

Here is the HTML code snippet:

<div class="data-item">
    <a class="title" id="cms-occasion" style="font-size: 14px !important;" href="#">Gift for a Graduate</a>
    <div></div>
</div>

<div class="data-item">
    <a class="title" id="cms-occasion" style="font-size: 14px !important;" href="#">Driving Experience Gift</a>
    <div></div>
</div>

<div class="data-item">
    <a class="title" id="cms-occasion" style="font-size: 14px !important;" href="#">Gift Ideas</a>
    <div></div>
</div>

Next, here is the JavaScript function I wrote that seems to have errors:

var giftIdea = document.getElementById('cms-occasion').innerHTML.indexOf('Gift Ideas');
if (giftIdea != -1){
    giftIdea.style.display = 'block';
    giftIdea.style.width = '100%';
    giftIdea.style.bottom = '-117px';
    giftIdea.style.textAlign = 'left'; //Changed from text-align
    giftIdea.style.position = 'absolute';
    giftIdea.style.backgroundColor = '#535353'; //Changed from background-color
    giftIdea.style.padding = '6px';

}

Could someone please help me identify the issues in my JS function?

Thank you in advance!

Answer №1

One important rule to remember in HTML is that you cannot have multiple elements with the same ID, as IDs are meant to be unique identifiers.

In JavaScript, using getElementById will only return one element. Your current selector retrieves the first element and then searches for a specific string using indexOf.

To target multiple elements, consider using classes instead of IDs and utilize document.querySelectorAll. You can filter the returned array like this:

document.querySelectorAll('.cms-occasion').filter(function(el){ return el.innerHTML.indexOf('Idees cadeaux') !== -1 })

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

Generate a customized form based on selected radio button option

Hey there! I'm curious to know if it's achievable to utilize Javascript/jQuery or Ajax in displaying a form depending on a radio button selection. Here's the scenario: I have two unique forms. If one radio button is chosen, I'd like to ...

Connect the CSS active state to a JavaScript event

.el:active{ background:red; } Is there a way to associate the above CSS active state with a JavaScript event, like this: $('.el').on('active', function(){ img.show(); }); I want the image to remain visible when el is presse ...

Fixing Bootstrap's Timeline Component

I've created a Bootstrap timeline that works well on mobile and small screens, but encounters some issues on larger devices. You can view it at https://codepen.io/irshad437/pen/rLvxxa. Feel free to resize your window to test its functionality, which s ...

Using Vue.js to dynamically populate all dropdown menus with a v-for loop

Getting started with vue.js, I have a task where I need to loop through user data and display it in bootstrap cols. The number of cols grows based on the number of registered users. Each col contains user data along with a select element. These select ele ...

Is it possible to combine Bootstrap 2.3.1 with newer versions such as 4.0 or 3.x.x?

My current website is built using Bootstrap 2.3.1, but now I am looking to update to a new version of Bootstrap. However, when I tried updating, the entire UI changed drastically and the website started to look clumsy. Instead of completely replacing the ...

Tips for initializing the store in Vue when the application first starts

Seeking assistance in loading products from my pinia store upon the initial load of my Vue app. Check out my app.js below: import {createApp} from "vue"; import App from "./App.vue"; import router from "./Router/index"; impor ...

What's the reasoning behind the name first-child?

Although I may receive many down votes, I am still curious to hear your opinions. If you have ever encountered the following code: <div> <p>Paragraph1</p> <p>Paragraph2</p> </div> <div> </div> lite ...

Connect the scroll wheel and then proceed to scroll in the usual way

There are two div elements with a height and width of 100%. One has the CSS property top:0px, while the other has top 100%. I have implemented an animation that triggers when the mousewheel is used to scroll from one div to the other. The animation functi ...

writing a react element in an object with an svg component

I am encountering difficulties when trying to type the following. The problem lies with the TeamIcon. Here is how my object is declared. import TeamIcon from './components/icons/TeamIcon'; export const teamObject: Record< string, Recor ...

Materialize CSS dropdown select arrow out of position

Here is a snapshot of the Materialize CSS, which can be viewed at: However, I am encountering an issue where the dropdown arrow appears below the list instead of on the side. I am currently using Django 3. How can I resolve this? https://i.sstatic.net/d ...

Cannot retrieve authorization cookie

Currently, I am in the process of setting up backend authentication using Express, Node, and Supabase for my frontend built with React. //auth.js import { supabase } from "../config/supabaseConfig.js"; export const checkAuthorizationStatus = asy ...

Guide on changing the background image of an active thumbnail in an autosliding carousel

My query consists of three parts. Any assistance in solving this JS problem would be highly appreciated as I am learning and understanding JS through trial and error. https://i.sstatic.net/0Liqi.jpg I have designed a visually appealing travel landing pag ...

Creating an interactive table with the power of FPDF and PHP

I have developed a unique Invoice System that allows users to customize the number of headings and fields using FPDF in conjunction with PHP. Subsequently, I can input the heading names and field values into HTML input fields. However, I am encountering a ...

Exploring the basics of caching in Node.js and Express: a beginner's

Picture an application with numerous users and small sets of data (up to 10 name/value pairs), but the process to access this data involves complex calculations. The concept is based on a system with a 'history' state that is crucial for obtaini ...

Is there a way to eliminate the 'All Files' option from an HTML file input field?

I have implemented a feature to allow users to upload custom files using . Currently, I am restricting the allowed file types to only ".Txt, .SVG, .BMP, .JPEG" by using accept=".Txt,.SVG,.BMP,.JPEG". This setting causes the browser's file-select dial ...

What is the process for defining a filename when exporting with Webdatarocks default settings?

I'm having a hard time figuring out how to set a custom name for the exported file instead of just "Pivot". The HTML/Vue part contains the Pivot along with a select dropdown for filtering by date, which is working fine. The issue lies in customizing t ...

Verification of sliding puzzle functionality in JavaScript

I have successfully created a sliding puzzle with various formats, including 3x3, 3x4, 4x3, and 4x4. When you run my code, you will notice a selection box on the right side where you can choose from these four formats. The sliding puzzle is almost complete ...

Display child component automatically upon parent component state update

The main component Dashboard manages the state for each ListItem added to my Watchlist. However, whenever I add an item, it is inserted into the database but only appears when I refresh the browser. class UserDashboard extends React.Component { state = ...

Including Vuetify in my project has triggered a SecurityError, specifically relating to the CSSStyleSheet.cssRules getter being restricted from accessing cross-origin stylesheets

Looking to create a Vue application that opens a CKEditor component in a separate window, I managed to do so following the method outlined in this helpful post. I have even set up a Codesandbox demonstration to showcase the functioning example. However, u ...

What is the method for executing a for loop in AngularJS without relying on HTML elements?

I'm creating an application in AngularJS where the structure requires me to execute a for each loop without using any HTML elements or div tags with ng-repeat. In Django, we typically use the following syntax: {% for item in list %} {{ item }} {% ...