Home > Software design >  Why text () and style. width is not working in Js?
Why text () and style. width is not working in Js?

Time:09-27

I have a HTML like the below,

<div id ="b1>
     <i class="icon-clock"></i> <span class="font-weight-bold font-size-lg" id="currentTime"></span>
</div>

I could not get the current date and time displayed in the particular Div.

Js:

 // To display Date and time
    
    var target = document.getElementById('b1');
    var today = new Date();

    var date =
      today.getFullYear()  
      "-"  
      (today.getMonth()   1)  
      "-"  
      today.getDate();

    var time =
      today.getHours()   ":"   today.getMinutes()   ":"   today.getSeconds();

    var dateTime = date   " "   time;

   $(target).find('#currentTime').text(dateTime); // It dosen't displays the current date and time

And I need a solution about how to add the Width to the progress bar like the below,

<div id = "b2">
    <div class="progress">
          <div class="progress-bar bg-success" id="div1" 
                style="width:0%">
           </div>
           <div class="progress-bar bg-warning" id="div2"
                style="width:0%">
           </div>
     </div>
</div>

If I use the below in the JS.

 var target = document.getElementById('b2');
 d1 = $(target).find('#div1');
 d2 = $(target).find('#div2');
 d1.style.width = 78   "%";
 d2.style.width = 22   "%";

I could get Uncaught TypeError: Cannot set properties of undefined (setting 'width').

Couldn't get the width for the progressbar. How to add the Width to the progress bar inside the particular div?

How to add the Current Date and time to the particular Id ?

Could anyone please help?

Many thanks.

CodePudding user response:

This is happening because you are assuming JQuery find() returns a DOM element on which style property exists. But in reality, it returns a jQuery Object.

You can use .css() jQuery method to make the change.

d1.css( "width", "78%" );

CodePudding user response:

So, for displaying the current date and time to a div I guess this could help you

Here is the script code example:

// get a new date (locale machine date time)
var date = new Date();
// get the date as a string
var n = date.toDateString();
// get the time as a string
var time = date.toLocaleTimeString();

// find the html element with the id of time
// set the innerHTML of that element to the date a space the time
document.getElementById('time').innerHTML = n   ' '   time;
   

And the div with id is as following:

<div id='time'></div>
  • Related