Javascript: getting element name by name does not work

I am working on a rich text editor and have succeeded so far. I made a separate .js file to use it as a plugin.

Now I want to use this plugin by assigning it a class name via a .cshtml file. But it does not seem to work, I was looking for relevant answers, and they said that using document.getElementsByClassName would solve my problem.

Read 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> 
+4
source share
5 answers

Just take the first element of matching nodes; this is a NodeList, but can be dereferenced as an array.

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

getElementsByClassName returns an array, so use

  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(); }); 
+3
source

why don't 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. 
+1
source

How do you use jQuery, why not use jQuery.

  var richTextEditor = $('.text-editor').eq(0); 

as well as the live jQuery method is deprecated, use .on() instead.

0
source

$ (". text-editor") returns an HTMl object. "document.getElementsByClassName (" text-editor ")" returns an array object.

0
source

All Articles