Javascript: Get element by class name not working

25,413

Solution 1

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

Solution 2

getElementsByClassName returns an array so use like this

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

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

Solution 3

why dont you use jquery methods??

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

instead try this:

var richTextEditor = $(".text-editor"); //again this is going to return more than  one object.

//so you can also try below code to manipulate in that.

var richTextEditor = $(".text-editor").first(); //for first element. similarly can use .last() or n-th child.
Share:
25,413
Manoz
Author by

Manoz

Web developer C#, .NET MVC, CORE Certified EPIServer Developer. Areas expertise with - C#, MVC, React, Node, Webpack, .NET Core, Web API, EPIServer CMS/CM

Updated on July 09, 2022

Comments

  • Manoz
    Manoz almost 2 years

    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>