1

I try to create a div element and read height from a CSS selector. finally change the div elemet height by javascript. When I use div.style.height ='15px'; work correctly but I want change height dynamically because my CSS class will change by responsive function.

My CSS is:

    #indicator {
        width: 15px;
        height: 15px;
    }

And I use this code for Script:

 div = document.createElement("div");// valve_indicator
 div.style.border = '1px solid #b3280a';

 div.style.height =document.getElementById('indicator').style.height; // instead div.style.height ='15px';
 div.style.width = '15px';
 cell.appendChild(div); // cell is a table cell

But document.getElementById('indicator').style.height return null. please help me thanks in advance

11
  • your code is incomplete,please edit your question with full js code Commented May 15, 2020 at 7:12
  • yes this code use in a for loop i edit it Commented May 15, 2020 at 7:23
  • you first created div tag but didn't append it to Dom,then you wanted to select it,absolutely the answer in null,must first append to Dom and then select it Commented May 15, 2020 at 7:33
  • However, you should not enter the # sign in the selector 'getElementById' Commented May 15, 2020 at 7:35
  • in next line I append it in a table cell cell.appendChild(div); I edit is Commented May 15, 2020 at 7:42

2 Answers 2

2

Remove the # in #indicator. getElementById() doesnt need # sign before the id name

document.getElementById('indicator').style.height

And if you want to dynamically change the indicator height:

let indicator = document.getElementById('indicator');
indicator.addEventListener("change", function(){
    div.style.height = indicator.style.height;
}) 
Sign up to request clarification or add additional context in comments.

3 Comments

Is your <script> tag at the end of your <body> tag? Your javascript code can not see indicator div before its been loaded.
when I use div[].style.height ='15px'; work correctly but I want change height dynamically because my CSS class is dynamic
I edited the question for dynamic change. This code should work if you are using script tag properly. Hope this helps.
0

I solve my problem by use this code

div.className='indicator';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.