Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

215
Views
Jquery append div and dynamically set the width

I'm trying to append a div to a td in a table. However, as I am appending the div, I want to first take the clientWidth of the td (to take into account different screensize) and then set the width of the div to be that width:

var tdWidth = document.getElementById("someId").clientWidth; // ex: 165

td.append("<div Div1 style='margin:auto; width:150px;'><div msg style='color:red'>" + "Text, Text, Text" + "</div></div>");

Now I'm trying to apply the 165 value to Div1 (where the width is currently hardcoded to 150px - I'd want to not hardocode it but dynamically set it), but I have no clue how to do this, I tried to do things like:

  $('Div1').width(tdWidth);

and

  var tdWidthPx= tdWidth + 'px';

  $('Div1).css("width",tdWithPx);

Ideally I would want to set the width as I append it so that when the text id displayed it is displayed in the correct width.

Thanks in advance.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

There is no HTML attribute called Div1 or msg. Hence, this becomes invalid HTML.

You can append the width like this without hardcoding it initially.

var tdWidth = document.getElementById("someId").clientWidth; // ex: 165

td.append("<div style='margin:auto; width:" + tdWidth + "px;'><div  style='color:red'>" + "Text, Text, Text" + "</div></div>");

Or else, you can assign an id and later change the width based on id.

var tdWidth = document.getElementById("someId").clientWidth; // ex: 165

td.append("<div id='Div1' style='margin:auto; width:150px;'><div style='color:red'>" + "Text, Text, Text" + "</div></div>"); // giving an id to the div element(this id should be unique)

The change the width using the id.

var tdWidthPx= tdWidth + 'px';

$('#Div1').css("width",tdWithPx);

Use the first method if you are not changing the div width dynamically later in the program.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!