updating the HTML DOM elements using JavaScript is not yielding any response

One way that I am trying to change the background of a div is by using a function. Below is an example of the html code I am working with:

$scope.Background = 'img/seg5en.png';
document.getElementById("Bstyle").style.background = "url("+$scope.Background+") no-repeat center fixed;";           
console.log(document.getElementById("Bstyle").style.background);
console.log("url("+$scope.Background+") no-repeat center fixed;");

Initially, the variable $scope.Background points to "img/bg.png" which was defined at the beginning of my document. The first console.log statement shows that the style.background value is "img/bg.png".

Strangely, the second console.log output displays:

url(img/seg5en.png) no-repeat center fixed
.

I am puzzled as to why my html page does not reflect this change in background image.

Answer №1

Please use AngularJS to modify the DOM in a more structured way

Utilize ng-style directive to dynamically change the style of an element through JavaScript.

With AngularJS, you can assign values to $scope variables which can be accessed in your view.

Here is a demonstration to help you resolve your issue:

function ChangeBackground($scope) {   
    
   $scope.Background = 'https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcQdNIsxlrqB0Bqy-qmamo6tt9fdqqL9p43Bf5oy11xt0UuAa9vAILYjMX7_';

  $scope.changeImage = function(){  
      $scope.Background ='https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcQ2I2AW0JI-scAY0Phe321d1Yi8UHbFhsIk8OXTbpfEfaNf9F4V9lt60rs';
   }

}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app ng-controller="ChangeBackground">
    <div ng-style="{'background': 'url(' + Background + ')'}"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla porttitor mi non consequat varius. Curabitur libero tellus, placerat in metus nec, porttitor facilisis mi. Vivamus nec mattis felis. Cras mattis in mi sed feugiat. Sed ut hendrerit nisi, at tincidunt nibh. Donec vel malesuada orci. Nunc auctor tortor in mi consectetur gravida. Phasellus eleifend erat lectus, convallis tincidunt nisi euismod et. Donec a ornare eros, et eleifend magna. Phasellus viverra pellentesque metus, in lacinia tortor egestas nec. Suspendisse luctus dolor sit amet nisi interdum, nec commodo orci consectetur. Phasellus pretium vulputate viverra. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
</div>
<input type="button" value="Change Background" ng-click="changeImage()"/>
</div>

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

Removing a row from a table does not delete it completely

Disclaimer: While I am aware of SQL Injection, my main focus is on getting the function completed. I'm having an issue with my delete button not removing the row from my SQL table. products-one-time.php This is the output of my foreach loop. The nu ...

Guidelines for inputting a value into a JavaScript list and choosing a specific item within the list

When it comes to studying Selenium Web, I rely on the website. My current challenge involves inputting 'Ottawa' into the location control and then selecting 'Ottawa, ON'. WebElement el = driver.findElement( By.xpath("//*[contains( ...

Filter JSON data in AngularJS ng-repeat by a specific ID

I'm having difficulty getting this to function properly. I've been attempting to filter a JSON file by specific ID and then iterate using ng-repeat. Here's what I have tried: This is the button trigger: <a href="#/compare-details">& ...

Failure to give an error message occurred during a POST request on Parse.com and ExpressJS platform

I'm facing an issue where a POST request I send fails with error code 500 and there is nothing showing up in my server side error log. It seems like the cloud method may be missing. What's interesting is that the same POST request works fine wit ...

Could the php function json_encode() be a security risk if used within a script tag?

A while back, I had read OWASP's XSS Prevention Cheat Sheet and created a wrapper function that included JSON_HEX_TAG|JSON_HEX_APOS|JSON_HEX_QUOT|JSON_HEX_AMP by default to ensure safety. However, a user on Freenode/##php pointed out that this approac ...

Application experiencing server error when updating MongoDB data

I have encountered an issue while trying to update/modify data that has already been uploaded in a reactjs project using mongoDB as the database. Whenever I attempt to update the data, an error is displayed. How can this problem be resolved? https://i.sta ...

The picture above just won't stay within the div

Ensuring my website is responsive across all devices has been a priority for me. However, I have encountered an issue where, upon scaling down the size of the web browser, an image positioned within a div starts to overflow. While attempting to address thi ...

What issue can be identified in this HTML/CSS code?

Here is the code snippet I am working with: http://jsfiddle.net/7jGHS/1299/ This is the HTML code: <div class="text1"><h2><span>THIS IS A TEST</span></h2> <p>1800 - 1570 - 000</p> <h2><span>T ...

React-dnd supporting multiple draggable and droppable elements

I am facing a challenge with making multiple elements draggable using react-dnd. I have an array of 4 fields that I would like to make draggable, but when I map through the array and give each element a className of 'element', they do not move as ...

The :first selector examines the parent's parent as a reference point, rather than the immediate

I am facing a challenge with shuffling large elements within my layout because of floating them and attempting to display them. Specifically, the elements with the class .gallery-large always need to be the first child inside the .item container. There are ...

How to style a CSS list and center-align it

My website features a <ul> list with submenus structured like this: <div id="cssmenu"> <ul> <li class='active'><a href='index.html'><span>Home</span></a></li> <li class=&ap ...

Strange height problem detected in embedded YouTube video

Currently, I have a page with an embedded YouTube video that is intended to be placed in a container with a variable width. When the video is outside of the container, the aspect ratio appears normal. However, once it is placed inside the container, the he ...

Limit of PHP string variable characters

I am working on an HTML survey where the answers are saved in variables and need to be inserted into a database using PHP. Here is an example of how the questions (part of a table) that can be filled out look like in HTML: <td style="padding-top: 10px ...

Alert displayed at the center of the browser when the value surpasses the specified number

My webpage retrieves SNMP data using PHP and displays it with HTML, color-coding the values. I want to add a pop-up alert when a value exceeds a certain number. I have attempted different jQuery solutions without success. The PHP code to get the value: ...

What is causing the compatibility issue between Ant Design V5 styles and NextJS?

Description In my NextJS project, I am using the Ant Design V5 framework with multiple pages. However, I am facing an issue where the styles are only working correctly on one page and not being applied properly on other pages. Despite referring to the off ...

It appears as though the promise will never come to fruition

I am currently developing an application that is designed to search for subdomains related to a specific domain and store them in a database. The application retrieves data from crt.sh and threatcrowd. One of the functions within the application parses th ...

Generate a fresh row in a table with user inputs and save the input values when the "save" button is

HTML: <tbody> <tr id="hiddenRow"> <td> <button id="saveBtn" class="btn btn-success btn-xs">save</button> </td> <td id="firstName"> <input id="first" type="tex ...

Disabling form with customized component in AngularJS

I’ve been trying to find a solution, but I’m stuck on this. I created a custom directive called manyToOneSelect that fetches items from the server, displays them to the user, and allows the user to select one item. It’s working fine, but I can’t fi ...

Ensure that you decode the URL before making any changes to the location in a

Hi everyone, I'm facing an issue and need your help. Let's say we have a URL like site.com/post?comments=1,2,3,4. When I paste it into the browser address bar, my app opens and decodes the URL to site.com/post?comments=1%2C2%2C3%2C4. How can I re ...

Select element from Material UI displaying horizontally

I'm brand new to Material Ui and currently tackling the implementation of their SELECT component. However, I am running into an issue where it is displaying in a row instead of a column. Am I overlooking something important here? const SelectDropDownC ...