Reputation: 2301
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?
Upvotes: 4
Views: 4589
Reputation: 39322
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>
Upvotes: 2
Reputation: 15292
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)
Upvotes: 0
Reputation: 6145
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>
Upvotes: 1
Reputation: 12012
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/
Upvotes: 0
Reputation: 2612
Give something id to span
<span id="span"></span>
$("#span").text(message.text);
Upvotes: 3