Bundyboy Bundyboy - 21 days ago 6
HTML Question

Why getElementsByClassName is not working while getElementById works?

this first code is not working

<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>

DN.onkeyup = DN.onkeypress = function(){
var div = document.getElementById("DN").value
document.document.getElementsByClassName("options-parameters-input").style.fontSize = div;
}


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

and this one works

<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>

DN.onkeyup = DN.onkeypress = function(){
var div = document.getElementById("DN").value
document.getElementById("one").style.fontSize = div;
}


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

Answer

getElementsByClassName returns array of object even though you have just one in your HTML. so you have ot use getElementsByClassName("options-parameters-input")[0] or whatever the index might be.