javascriptjqueryhtmlcss

Why getElementsByClassName is not working while getElementById works?


This first code is not working

DN.onkeyup = DN.onkeypress = function(){
  var div = document.getElementById("DN").value
  document.document.getElementsByClassName("options-parameters-input").style.fontSize = div;
}
#one{
    height:100px;
    width:100px;
    background-color:#CCCCCC;
    border:none;
    margin:10px;
    float:left;
}
<div id="one">
  <div class="options-parameters-input">
    gfdgd
  </div>
</div>
<br /><br /><br /><br /><br /><br /><br />
<table width="750" border="1" cellspacing="3" style="float:left;">
  <tr>
    <td>Test</td>
    <td><textarea id="DN"></textarea></td>
  </tr>
</table>

http://jsfiddle.net/gxTuG/85/

and this one works

DN.onkeyup = DN.onkeypress = function(){
  var div = document.getElementById("DN").value
  document.getElementById("one").style.fontSize = div;
}
#one{
    height:100px;
    width:100px;
    background-color:#CCCCCC;
    border:none;
    margin:10px;
    float:left;
}
<div id="one">gfdgd</div>
<br /><br /><br /><br /><br /><br /><br />
<table width="750" border="1" cellspacing="3" style="float:left;">
  <tr>
    <td>Test</td>
    <td><textarea id="DN"></textarea></td>
  </tr>
</table>

http://jsfiddle.net/gxTuG/86/

in first code i am trying to use getElementsByClassName and it does not work...

Error: Uncaught TypeError: Cannot read property 'getElementsByClassName' of undefined(…)

So my question is how to get working when I want to target element like div class ?

My goal is to make ability in options page panel that admin user can change / inject new css rules from textarea or input for certain elements. and there are elements like div class social-container-icons and other.

Also is this good way to inject new css rules ?

Thank you


Solution

    1. Better use with addEventListener(). First declare with DN. Then call the value of the DN via this.value. Because it's the same function in the element.

    2. And catch the ClassName like document.getElementsByClassName("options-parameters-input")[0]. It ends with [0]. Class matches multiple elements, so identify which one with [0] to match the first one

    3. Value of fontSize should end with px

    var DN = document.getElementById("DN");
    DN.addEventListener("keyup", both);
    
    function both() {
      document.getElementsByClassName("options-parameters-input")[0].style.fontSize = this.value + 'px';
    }
    #one {
        height: 100px;
        width: 100px;
        background-color: #CCCCCC;
        border: none;
        margin: 10px;
        float: left;
    }
    <div id="one">
    <div class="options-parameters-input">
    gfdgd
    </div>
    </div>
    <br /><br /><br /><br /><br /><br /><br />
    <table width="750" border="1" cellspacing="3" style="float:left;">
      <tr>
        <td>Test</td>
        <td><textarea id="DN"></textarea></td>
      </tr>
    </table>