Javascript: Get element by class name not working

Manoz picture Manoz · Mar 21, 2013 · Viewed 24.9k times · Source

I am working on rich text editor and did well till now. I've made a separate .js file to use it as a plugin.

Now i want to use this plugin by giving it a class name through .cshtml file.But it doesn't seem to work, i've searched for related answers and they said using document.getElementsByClassName will solve my problem.

Please go through this code and tell me what went wrong?

Text editor .js-

var richTextEditor = document.getElementsByClassName("text-editor");
    richTextEditor.contentDocument.designMode = 'ON';
    $('#strong').live('click', function () {
        richTextEditor.contentDocument.designMode = 'ON';
        richTextEditor.contentDocument.body.contentEditable = true;

        richTextEditor.contentDocument.execCommand('bold', false, null);
        richTextEditor.focus();
    });

cshtml file-

<script src="/js/Texteditor.js" type="text/javascript"></script>
<script src="/js/jquery.js" type="text/javascript"></script>
 <div  id="strong" class="command btn"><i class="icon-bold icon-black"></i></div>



    <iframe id="edtNoteCreate" class="text-editor"  name="DisplayNote" style="width:430px;height:150px;">@((Model.Note != null ? Model.Note : ""))</iframe>

Answer

Ja͢ck picture Ja͢ck · Mar 21, 2013

Just take the first item of the matched nodes; it's a NodeList but can be dereferenced like an Array.

var richTextEditor = document.getElementsByClassName("text-editor")[0];