Retrieve the accurate placeholder color using JavaScript

I modified the default placeholder color of my input to blue. How come I am seeing a black placeholder color when using JavaScript?

const fetchPlaceholderColor = () => {
  let inputElement = document.querySelector('.myClass');
  let inputElementStyle = window.getComputedStyle(inputElement, '::placeholder');
  
  let resultContainer = document.getElementById('colorOutput');
  let placeholderColor = inputElementStyle.getPropertyValue('color');
  resultContainer.innerHTML = `Placeholder color: ${placeholderColor}`;
}
.myClass::placeholder {
  color: #004085;
}

.marginTop20 {
  margin-top: 20px;
}
<input
  type="text"
  placeholder="Enter name"
  class="myClass"
/>

<button onClick="fetchPlaceholderColor()">Fetch placeholder color</button>

<div class="marginTop20" id="colorOutput"></div>

Answer №1

If you're interested in learning more about the topic, check out this resource: https://css-tricks.com/almanac/selectors/p/placeholder/

Take a look at this CodePen example that demonstrates the use of :placeholder-shown and ::placeholder:

https://codepen.io/kipomaha/pen/pOOdQr

document.getElementById("myStyles").sheet.insertRule('.myClass:placeholder-shown { color: red; }');
document.getElementById("myStyles").sheet.insertRule('.myClass::placeholder { color: red; }');
const getPlaceholderColor = () => {
    let inputEl = document.querySelector('.myClass');
    let inputElStyle = window.getComputedStyle(inputEl, ':placeholder-shown');
    let resultTarget = document.getElementById('colorResult');
    let placeholderColor = inputElStyle.getPropertyValue('color');

    resultTarget.innerHTML = `Placeholder color: ${placeholderColor}`;
}


document.getElementById("myStyles").sheet.insertRule('.myClass:placeholder-shown { color: red; }');
document.getElementById("myStyles").sheet.insertRule('.myClass::placeholder { color: red; }');

var inputEl = document.querySelector('.myClass'); 
var placeholderColor = inputElStyle.getPropertyValue('color');
const getPlaceholderColor = () => {
    let inputElStyle = window.getComputedStyle(inputEl, ':placeholder-shown');
    let resultTarget = document.getElementById('colorResult');

    resultTarget.innerHTML = `Placeholder color: ${placeholderColor}`;
}

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 your jQuery .on function failing to properly detect click events?

Seems like I'm missing something here. Why is the .on function not functioning as expected in this code snippet? <html> <head> </head> <body> <button type="button" class="close" data-test="test">TEST BUTTON< ...

Filter search results to display only posts

My website uses a custom Wordpress theme that has a search functionality. The issue I'm facing is that when I perform a search, it redirects me to the search.php page. However, instead of just displaying posts, it also shows pages and events from the ...

Using HTML5 to Define the Size of a File Upload Button

The validation error from W3C states: "Attribute size is not permitted for the input element at this location." <input type="file" name="foo" size="40" /> How should the width of a file input be specified in HTML5? ...

Steps to update the value of an object stored within an array

I have a collection of items stored in an array. Each item is represented by an object with properties. I want to update the value of a specific property within each object: var array=[{a:1, b:false}, {a:2, b:true}, {a:3, b:false}] My goal is to set the p ...

The installation of the material ui package was unsuccessful

C:\Users\User\Desktop\client4>npm i @material-ui/icons npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: [email protected] npm ERR! Found: [email protected] ...

Unable to utilize the resolved value received from a promise and returned from it

Within the code snippet below, I am retrieving a Table object from mysql/xdevapi. The getSchema() and getTable() methods return objects instead of promises. The purpose of this function is to return a fulfilled Table object that can be used synchronously i ...

What is the best way to find out if an array index is within a certain distance of another index?

I'm currently developing a circular carousel feature. With an array of n items, where n is greater than 6 in my current scenario, I need to identify all items within the array that are either less than or equal to 3 positions away from a specific inde ...

Screening data entries

.js "rpsCommonWord": [ { "addressWeightPct": "60", "charSubstituteWeightPct": "15", "nameWeightPct": "40", "oIdNumber": "21", "shortWordMinLthWeightPct": "100", "substituteWeightPct": "5", ...

"Encountered an issue while attempting to send the message: Unable to retrieve data" while utilizing NextJS and the

Currently, I am utilizing fetch along with NextJS to attempt to send information such as name, phone number, email, company, and message to an API. However, I am encountering an issue where the error message simply states 'Failed to fetch' in the ...

There seems to be an issue with Vue JS slots[name$1].every function as it is

I attempted to implement a custom isEmpty function for the Object prototype as follows: Object.prototype.isEmpty = function() { for (var key in this) { if (this.hasOwnProperty(key)) { return false } } return true } However, when tryin ...

What is the best way to upload a local image using JavaScript for TensorFlow?

I am having trouble loading a data.jpg file to be used by tensorflow mobilenet. When I try to require the file normally, I encounter an error message: So, my question is how can I load an image in my JavaScript code for use? I have tried various methods of ...

Unable to retrieve session information from a different PHP page

I have been searching for solutions here but haven't had any luck so far. I am currently learning HTML and while working on a simple login feature, I have run into some issues. I am using XML as a makeshift "database" and PHP to retrieve the informati ...

Executing a JavaScript function to submit an HTML form and circumvent the default behavior

Currently, I am utilizing a virtual keyboard that was created using JavaScript for the user interface on an embedded system. If you would like to access the source code for this virtual keyboard, you can find it here: https://codepen.io/dcode-software/pen ...

What could be the reason the background-color isn't changing when I apply button:hover?

body{ font-family:"Arial","Lucida Grande", "Lucida Sans Unicode", Verdana, Helvetica, sans-serif; font-size:12px; } p, h1, form, button{border:0; margin:0; padding:0;} .spacer{clear:both; height:1px;} /* ----------- My Form ----------- */ .myform{ margin:0 ...

I am struggling to grasp the concept of how the g flag in JavaScript's string.match(regexp) method operates

In the JavaScript book "The Good Parts", there is an explanation of the method string.match(regexp): The match method works by comparing a string with a regular expression. Its behavior varies based on whether or not the g flag is present. Without the g ...

Encountered a problem with Google API during the execution of Vue mounted hook

Looking for some help with this issue. I've loaded the Google map API on the created hook of the parent component, but I keep running into the following error message: Error in the created hook: ReferenceError: google is not defined Here is the code ...

Clicking the mouse within three.js

I'm facing an issue with my webpage that features a three.js (webgl) graphic created using a .dae file imported from Blender. My goal is to draw a square or mark wherever the mouse is clicked, but for some reason, the square appears in a different loc ...

AngularJS is not showing the dropdown options as expected

I am facing an issue where the dropdown list options are not displaying, even though I am able to fetch the data in the controller but not in HTML. Here is the code snippet: In HTML <select name="nameSelect" id="nameSelect" ng-model="model.name"> ...

reCAPTCHA v3 - Alert: There are no existing reCAPTCHA clients available

After coming across a similar issue on Stack Overflow (link to the question here), I attempted to implement reCAPTCHA on my website to combat spam emails received through the form. Despite following Google's instructions, I encountered an error that p ...

Sending Data to a PHP Script

I attempted to use the code below to send values to another PHP page but I am not receiving any output. File: Send.html <form id="form1" action="get.php" method="get"> <input name="search_name" type="text" id="search_name" size="20.5" height="45 ...