'Get content of span

how can I get the contents of span ? I'm looking for a way for all of this to be vanilla, not jQuery

javascript (and a little 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's 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>

Thank You



Solution 1:[1]

Give this a shot:

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

Solution 2:[2]

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>

Solution 3:[3]

There is an issue here:

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

You never assigned the text of the input to any variable.

Following your pattern above, you could do:

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

The second variable updates the previous variable 'txt' to hold 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;

Solution 4:[4]

Instead of using...

text.text();

Try using...

text.innerHTML;

I've only found .text() to work when you're using a jQuery selector.

 $('#myInput').text();

Solution 5:[5]

var text = (document.getElementById("myInput")).innerHTML

or the abridged form:

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dimitar Dimitrov
Solution 2 Joseph
Solution 3 Josh Beam
Solution 4 photodow
Solution 5 DevonDahon