3

I have an object:

message: {
    text: "Here is some text"
}

I want to insert it into a span tag like this:

<span>message.text</span>

This won't print 'Here is some text', instead it will just show 'message.text' on the webpage. How can I get it to show the actual contents of the object?

MonkeyOnARock
  • 2,151
  • 7
  • 29
  • 53

5 Answers5

2

Give something id to span

<span id="span"></span>
$("#span").text(message.text);
Nitin Dhomse
  • 2,524
  • 1
  • 12
  • 24
  • 1
    This example uses jQuery, which is fine, because jQuery is excellent in manipulating the DOM. However it's a good habit to learn how JavaScript works behind the library/framework. – cezar Jul 20 '16 at 10:13
2

With Plain JavaScript:

document.getElementsByClassName('text-holder')[0].textContent = message.text;

var message = {
    text: 'Here is some text'
};
document.getElementsByClassName('text-holder')[0].textContent = message.text;
<span class="text-holder"></span>

With jQuery:

var message = {
  text: 'Here is some text'
};

$('.text-holder').text(message.text);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<span class="text-holder"></span>

With AngularJS:

var app = angular.module('myApp', []);

app.controller('myController', function($scope) {
  $scope.message = {
    text: 'Here is some text'
  };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
  <div ng-controller="myController">
    <span>{{message.text}}</span>
  </div>
</div>
Mohammad Usman
  • 37,952
  • 20
  • 92
  • 95
1

A simple solution using vanilla js (strictly since you didnt use the jquery tag in your question) with working snippet:

function doAction() {
  var messageObj = {
    text: "Here is some text"
  }

  document.getElementsByTagName('span')[0].innerText = messageObj.text;
}
<span>PLACEHOLDER</span>
<button onclick="doAction()">do</button>
Iceman
  • 6,035
  • 2
  • 23
  • 34
0

You can do it with using tag name.

document.getElementsByTagName('span').textContent(message.text);

OR can assign some class or id to the span

<span id="my_id"></span>

document.getElementById('my_id').textContent(message.text);


<span class="my_id"></span>

document.getElementsByClassName('my_id')[0].textContent(message.text);

Using jQuery,you can do like this

$(".my_id").text(message.text)

OR

$("#my_id").text(message.text)
RIYAJ KHAN
  • 15,032
  • 5
  • 31
  • 53
0

If you're using plain HTML and vanilla JavaScript, then why should something else but message.text appear within the span tags.

Using just plain JavaScript you could do something like:

var message = {
    text: "Here is some text"
};
var spans = document.getElementsByTagName('span');
var el = spans[0];
el.innerText = message.text;

Here is a JSFiddle:

https://jsfiddle.net/k1q9jo5n/

cezar
  • 11,616
  • 6
  • 48
  • 84