Can't get height of dynamic created button using jquery

3015 views javascript
6

What I have:

I dynamically create a button and try to access the button width. In this example I'm doing console.log() but in my real case I want to use that value for other things.

let deleteButton = $(document.createElement("button"))
                            .addClass("deleteButton")
                            .text("delete")
                            .click(function(){
                                delete(this);
                            });

console.log($(deleteButton).width());

The Problem:

Buttons have a width and height by default, but the console.log() shows zero.

How to get the default width and height of the button?

Observation: The most likely answer to be accepted is using .width() like functions of jquery or explain why that function is not working and show a better solution.

answered question

Can you make a pen file and share

1 Answer

9

The function $.with() gets the current computed width for the first element in the set of matched elements.

Basically, that element wasn't rendered/processed by the engine, so the width is not available before it's added to the DOM tree.

let deleteButton = $(document.createElement("button"))
  .addClass("deleteButton")
  .text("delete")
  .click(function() {
    delete(this);
  });

// Here the engine will render/process this element.
$(document.body).append(deleteButton);

console.log($(deleteButton).width());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

posted this

Have an answer?

JD

Please login first before posting an answer.