Skip to content Skip to sidebar Skip to footer

Insert Value Of Object Into Span Tag

I have an object: message: { text: 'Here is some text' } I want to insert it into a span tag like this: message.text This won't print 'Here is some t

Solution 1:

Give something id to span

<span id="span"></span>
$("#span").text(message.text);

Solution 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;
<spanclass="text-holder"></span>

With jQuery:

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

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

With AngularJS:

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

app.controller('myController', function($scope) {
  $scope.message = {
    text: 'Here is some text'
  };
});
<scriptsrc="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script><divng-app="myApp"><divng-controller="myController"><span>{{message.text}}</span></div></div>

Solution 3:

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

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

  document.getElementsByTagName('span')[0].innerText = messageObj.text;
}
<span>PLACEHOLDER</span><buttononclick="doAction()">do</button>

Solution 4:

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/

Solution 5:

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);


<spanclass="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)

Post a Comment for "Insert Value Of Object Into Span Tag"