What are some ways to style an image that has been added using JavaScript using CSS?

I utilized a JavaScript function to add an image, which looked like this:

function show_image(src) {
  var img = document.createElement("img");
  img.src= src;
  document.body.appendChild(img);
}

But when I attempt to change its style using CSS:

    img {
     //style attributes etc.
}

The image does not respond. How can I resolve this issue?

Answer №1

To achieve a solution, consider manipulating CSS using JavaScript:

Include CSS within your function:

function display_image(source) {
var image = document.createElement("img");
image.src = source;
document.body.appendChild(image);
$(document).find(image).css(apply your styles here);
}

For instance: $(your element).css("color", "red");

VIEW REFERENCE

Answer №2

Styling elements with CSS should generally not cause any issues. But if you do encounter problems, one workaround could be applying the desired style or class using JavaScript instead.

Answer №3

Add a CSS class name to the intended image element

function display_image(url) {
  var new_img = document.createElement("img");
  new_img.src = url;
  new_img.className = "custom-class";
  document.body.appendChild(new_img);
}

To style the image, define the custom class in your CSS file

.custom-class {
    border: 1px solid #000;
}

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 ng-model feature is unable to properly save data within a nested ng-repeat function for a 2-dimensional array

I'm currently working with a nested ng-repeat on a 2d array and have added ng-model to the third ng-repeat. However, I am encountering an issue where my ng-model is not properly storing the data within the object. JavaScript Code emrService .getDat ...

Switch between various height and width options using JavaScript

Is there a way to create a toggle that changes both the height and width of an element when it is clicked? <div class="flexbox-container" id="main" onclick="staybig()">Create Account</div> .flexbox-container { ...

Experiencing an issue while rendering due to the presence of display: table-cell;

I am currently in the process of developing a website. The HTML Header section is structured as follows: <div id="page"> <header> <a href="#" class="redsquare">&nbsp;</a> <div class="head-wrapper"> ...

How can one effectively manage irregularly nested object/arrays within a Meteor framework?

Having difficulty finding a smart and effective method to manage nested arrays/objects with varying dimensions in nodeJS. These irregular arrays/objects can have 1, 2, 3, or more dimensions. For instance, consider these 2 different scenarios : Scenario 1 ...

PHP and special characters from other languages

Struggling with writing non-English characters to a file (.txt) using PHP. Here's the code snippet: $str = "â€êþÿûîœøîô‘ë’ðüïlæ߀¿×÷¡ï"; $str = htmlentities($str, ENT_QUOTES, mb_detect_encoding($str)); $str = htmlspecialc ...

Is it okay to incorporate this code into the existing plugin?

My plugin, known as "pluggable," has the ability to take any element with the class .plugin and inject the following markup into it: <span class="colorable">color me</span> Below is the original markup containing elements with the class "plug ...

Adding options to a dropdown menu using jQuery and Ajax technique

After retrieving data from an Ajax call and attempting to append option values to a dropdown generated in jQuery, it doesn't seem to be working as expected. Here is the code snippet: $(document).on('focusout', '.generate', functio ...

How can I implement checkboxes for each row in tables using AngularJS?

Looking to include a checkbox for each table row in AngularJS that, when checked, will send the value to the controller. Can someone assist me with accomplishing this? Below is my index1.html <html ng-app> <title>Angular Table</title> & ...

What is the method for configuring a timezone in Selenium Chromedriver?

I'm struggling to set a specific timezone while using Chromedriver. Is there an argument in ChromeOptions that can help with this? The problem arises when I visit certain websites (such as ), where it displays the system time based on Windows setting ...

Avoiding redundant data in CRUD applications

In a CRUD application (back-end using express and front-end using react-redux), form values are submitted to a mongodb database with the following schema: import mongoose from 'mongoose'; var Schema = mongoose.Schema({ createdAt:{ type: D ...

Problem with items overlapping in hoverable drop-down menu

I have been attempting to create a hoverable dropdown menu, but I am encountering an issue where the items of the dropdown are overlapping. Despite my efforts to adjust the CSS classes, I have not been successful in fixing this problem. Additionally, I ha ...

The function react_jsx_dev_runtime__WEBPACK_IMPORTED_MODULE_4__.jsxDEV(...) is not recognized

For my react-redux project, I utilized json-server as the server for managing orders. The status of each order is saved in the state within UiReducer and is then accessed in the "OrderStatusPage". The current NODE_ENV configuration is set to "development". ...

Display all the names of the files from various file inputs in a unified notification

I have developed a function that checks if the selected file names already exist in the database. It currently alerts a message for each file name found in the database, which can be overwhelming with multiple files. I am looking for suggestions on how t ...

Anchor tag remains in fixed location in HTML

Here's a link that I need help with: <a id="readmore" href="#">READ MORE</a> Currently, when the user clicks on this hyperlink, I am using Jquery to toggle the content below it to show/hide the content. However, I have encountered an ...

Exploring the possibilities of page manipulation using React Native WebView

I'm encountering an issue with my implementation of react-native-webview. When I use it to open a webpage, the audio doesn't start playing automatically. Instead, I have to press a button for it to play. Is there a way to make the audio play dire ...

Troubleshooting the compatibility issue between Gravityforms and Jquery File Upload

I want to integrate the JQuery File Upload plugin with Gravity Forms in Wordpress. I've set up a form with a file upload input where Gravity Forms has assigned the field id as input_1_33. This id is being used for the file upload jQuery plugin. jQuer ...

Exploring the world of jQuery events with JSON data processed through Popcorn

Has anyone experienced issues with jquery events not working when using json data parsed through Popcorn.js JSON Parser? I am trying to trigger a function when a specific link is clicked, which is included in the json file. The parsing process seems to be ...

Having trouble deactivating date selections in Vue.js Material Datepicker

Can someone assist with the following HTML code: <datepicker :date="child" :option="option" v-model="child.dob" @change="updatechildDOB(child)" :disabled="disabled"></datepicker> Here are the available options: option: { type: 'd ...

The true screen resolution of Safari on iPhone devices

I'm feeling a bit lost right now. Currently, I am using Jquery Mobile and here is my code: <meta content='width=device-width, minimum-scale=1.0, maximum-scale=1.0,user-scalable=no' name='viewport'> When I ran the following ...

Creating a layout with Bootstrap 4 cards split into two rows

I need to change my layout from 3 columns to 2 columns. I know I can achieve this using CSS like the code snippet below, but I'm curious if there's a built-in Bootstrap method for this: .card-columns { -webkit-column-count: 2; -moz-column-co ...