0

i am trying to give margin-top:10px to id download-csv

Here is html and javascrpit:

<span style="display: inline;"  id="download-csv"><input type="submit"   id="csv_download"  value="Download"></span>;



JavaScript :
         var download_csv=document.getElementById("download-csv");
if(count_layer==1)
        download_csv.setAttribute("style","margin-top:10px");
}else{
       download_csv.setAttribute("style","margin-top:20px");

}

Its throws error TypeError: Cannot read property 'setAttribute' of null

0

3 Answers 3

4

You need to ensure that markup is loaded before those elements are accessed by the JS code.

Also, you cannot give margins to inline elements, set display style property as display-inline.

var download_csv = document.getElementById("download-csv");
var count_layer = 1;
if (count_layer == 1) {
  download_csv.style.marginTop = "10px";
} else {
  download_csv.style.marginTop = "50px";
}
<span style="display: inline-block;" id="download-csv">
   <input type="submit"   id="csv_download"  value="Download">
</span>

Sign up to request clarification or add additional context in comments.

Comments

2

You can try this code :

if(count_layer==1)
        download_csv.style.marginTop = "10px";
}else{
       download_csv.style.marginTop = "20px";
}

3 Comments

sorry to write double time style.style it is the only style one style try this again, please.
Sir i wrote this one but Same error download_csv.style.marginTop = "10px";
Welll Thanks Sir
1

Now your javascript code is being executed before the page loads, thus the <html>attribute won't be loaded yet, and then you will get the error.

To fix it, put your javascript code inside $(document).ready

$(document).ready(function() {
    //Your code goes here
}) ;

2 Comments

Not sure if this guy is using jquery
Mostly JavaScript

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.