Skip to content

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.

Answer

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.