What is the best way to connect CSS properties to an image using JavaScript?

I recently used JavaScript to insert an image into a webpage, but I'm unsure of how to make changes to it or position it properly. Is there a way to connect CSS styles to the image, or is there another method to modify it without relying on CSS?

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8>
    <title>Custom Image</title>
    <link rel="stylesheet" href="CSS/style.css">
</head>
<body>


 <script>

    function displayImage() {
  var img = new Image();
  img.src = 'img/custom.jpg';
  document.body.appendChild(img);


}


    </script>

<p>Check out this image below:

   <script>
    displayImage();
    </script>

   </p>


</body>
</html>

Answer №1

Utilizing JQuery can simplify this process greatly. You can apply various styles to an image by editing the style attribute within the image tags.

<!doctype html>
<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    </head>

    <body>
        <p> Take a look at the following image: </p>

        <script>
            window.onload = function(){
                addImage();

                function addImage() {
                    $('body').append('<img style="insert any CSS styling here" src="img/ilona.jpg">');
                }
            }
        </script>
    </body>
</html>

Answer №2

One of the features of Javascript is its capability to modify an element's attribute.

img.setAttribute("style", "background-color: red;");

Visit this link for more information.

If you prefer not to use inline CSS, another approach would be to include the CSS in your CSS file and assign a class to the image using jquery.

$("img").addClass("myImage");

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

What is the mechanism behind Angular or JS retrieving data without the need for defining a parameter name?

The title of this question may not fully capture what I am trying to ask. To provide more clarity, consider the following example: .service('Book', function($http) { var bookService = {}; Service.getBook = function() { return $http.g ...

Guide on establishing a connection between Firebase Cloud Functions and MongoDB Atlas

I am currently attempting to connect to a MongoDB Atlas database from cloud functions by following the guidance provided in this answer. The code snippet I am using is as follows: import { MongoClient } from 'mongodb' const uri = 'mongodb ...

Is there a way to verify if the request query value is empty like ""?

When creating a Node.js component, I encountered an issue with one of my APIs that sometimes returns empty query values like "". In order to handle this scenario, I need to implement a conditional statement. For example, the query may look like this: { ...

What is the method for obtaining the image alt attribute using JavaScript?

I can't seem to retrieve the image alt tag using JavaScript. Is it even possible and if so, how should I go about it? Perhaps something like this: $caption.text( flkty.selectedElement ).attr('alt') (last line of JavaScript) But I'm st ...

How can a Chrome extension transfer an ArrayBuffer or Blob from a content script to the background script without compromising its data type?

In my current script, I am downloading binary data using XHR in the content script and sending it to the background script: let me = this; let xhr = new XMLHttpRequest(); xhr.open('GET', url); xhr.responseType = 'arraybuffer'; xhr.onlo ...

Toggle the class of a div when clicked and then change the class of another div

In my website, I have a site overlay Div (#site-overlay) that is currently set as display:none. I am looking to change the class to block when I hover and click on the menu buttons. I can use both vanilla JavaScript and jQuery to achieve this. The menu it ...

The Angular currency filter is displaying a strange blank space despite the correct syntax being used. Is there anyone who can assist me with this issue?

Hey everyone, I'm having some trouble with the currency filter in Angular. It's not working and just displaying a blank space. I'm new to learning Angular so any help would be greatly appreciated! Here is the code I'm using: <!DOCT ...

Changing the Style of a CSS Module Using JavaScript

Embarking on a journey into Javascript and React, I am currently working on my first React app. My aim is to adjust the number of "gridTemplateRows" displayed on the screen using a variable that will be updated based on data. Right now, it's hardcode ...

Show a specific form field based on the chosen option in a dropdown menu using Angular and TypeScript

I am looking to dynamically display a form field based on the selected value from a dropdown list. For instance, if 'first' is chosen in the dropdown list, I want the form to remain unchanged. However, if 'two' is selected in the drop ...

What is the best way to retrieve data from a POST request?

I am attempting to post data from the same site and create a new order when the submit button is clicked. However, I am not receiving any information in my req.body, leading me to suspect that there may be an issue with my ejs file. Any feedback on this ma ...

Tips for converting an asynchronous process to operate as a synchronous process

Hey there! Checkout this piece of code I have function executeBat(){ var process = require('child_process').exec; process('C:\\Temp\\tasks\\acis\\runme.bat', function(error, stdout, std ...

Swapping values in JSON by comparing specific keys: A guide

I have JSON data that contains a key called reportData with an array of values: {"reportData":[ ["1185","R","4t","G","06","L","GT","04309","2546","2015","CF FE","01H1","20","23840","FF20"], ["1186","R","5t","R","01","L","TP","00110","1854","2016" ...

Is it possible to navigate back to a component in Angular without having to reload it?

Within my Angular application, there is a main component that contains various child components. This main component includes logic for showing and hiding components based on certain conditions. <div *ngFor="let data of dataSource; let i=index"> & ...

Using Vue.js to send a slot to a child component in a nested structure

Check out this interesting modal component configuration //modal setup <template> <slot></slot> <slot name='buttons'></slot> </template> Imagine using it like a wizard //wizard setup <template> ...

What steps should I follow to generate a table using Ajax and Javascript when a button is clicked?

After spending hours following various tutorials and exploring previously asked questions, I am struggling to make this work. My HTML page looks like this: <!DOCTYPE html> <html> <head> <link type="text/css" rel="styleshee ...

Clickable link in popup window using fancybox

When I try to use fancybox to open an iframe and scroll to an anchor tag, it works perfectly in IE but not consistently in other browsers. It stops at a different place than the anchor. I suspect the issue may be related to JavaScript based on information ...

What is the best way to smoothly hide and reveal a flex child element?

I am looking to create a flex container where the child element can smoothly animate to shrink and grow, while the remaining child elements expand to fill in the space. The method I have found involves setting the max-width to 0px and the borders' wi ...

Troubleshooting Problems with Retrieving Data Using jQuery and

Having trouble fetching information from a JSON file, as the data variable is empty. I have already downloaded the JSON file, so it's not an issue with the server connection. Can anyone point out where I might be going wrong? function handle_geolocat ...

Tips for preventing redirection in Vue 3 composition API with asynchronous requests

I have successfully configured a submission form to send data to my email and add it to a Google sheet using the method described in this GitHub link. The process worked seamlessly for both purposes. However, I am facing an issue where upon submitting the ...

Showcasing the values of JavaScript

How can I resolve the issue depicted in the second picture? I need the value of 3 only in the USD column, with all others having a value of zero. <div class="span3"> <ul class="nav nav-tabs nav-stacked" > <?php foreach ( ...