Get Range Content

How can I get the contents of a range? I'm looking for a way to make it all be vanilla and not jQuery

javascript (and a bit of jQuery)

var swear_words_arr=new Array("bad","evil","freak"); var regex = new RegExp('\\b(' + swear_words_arr.join('|') + ')\\b', 'i' ); function validate_user_text() { var text = document.getElementById('myInput'); text.text(); if(regex.test(text)) { window.location="http://www.newlocation.com"; return false; } } var myVar=setInterval(function(){validate_user_text()},1000);change 

here is my html

 <div id="textArea"> <span id="myInput" contenteditable="true">kfjdkfj</span> </div> <br /> <form name="form1" method="post" action=""> <textarea rows="3" cols="40" name="user_text" style="border:2 solid #808080; font-family:verdana,arial,helvetica; font-weight:normal; font-size:10pt" onclick="select_area()"></textarea> <br /> <input type="button" value="Submit" onclick="return validate_user_text();"></form> 

thanks

+6
source share
5 answers

Take a picture:

 var input = document.getElementById("myInput"); var text = input.innerHTML; 
+13
source

You can use textContent

Taken from MDN:

 // Given the following HTML fragment: // <div id="divA">This is <span>some</span> text</div> // Get the text content: var text = document.getElementById("divA").textContent; // |text| is set to "This is some text". // Set the text content: document.getElementById("divA").textContent = "This is some text"; // The HTML for divA is now: // <div id="divA">This is some text</div> 
+8
source

There is a problem here:

 var text = document.getElementById('myInput'); text.text(); 

You have never assigned input text to any variable.

Following the above pattern, you can do:

 var txt = document.getElementById('myInput'), txt = text.text(); 

The second variable updates the previous txt variable to store the text of the original txt variable, which was a selector.

You could do this as well (vanilla javascript, jsfiddle ):

 var txt = document.getElementById('myInput').innerHTML; //or var txt = document.getElementById('myInput').textContent; 
+3
source

Instead of using ...

 text.text(); 

Try using ...

 text.innerHTML; 

I just found .text () to work when you use jQuery selector.

  $('#myInput').text(); 
+1
source
 var text = (document.getElementById("myInput")).innerHTML 

or abbreviated form:

 var text = $('#myInput').text() 
0
source

All Articles