Dennisluzern Dennisluzern - 1 year ago 153
HTML Question

How do I change the text of a span element in JavaScript?

Basically, I can use this method only for image. The question is how can I use this method for text types.

Image Method:

<a href="#"><img id="random"></a>
<script>
var image = new Array ();
image[0] = "image1.jpg";
image[1] = "image2.jpg";
image[2] = "image3.jpg";
image[3] = "image4.jpg";
var size = image.length
var x = Math.floor(size*Math.random())

$('#random').attr('src',image[x]);


Text HTML look like this:

<span id="xx" href="#" class="text-ellipsis">Text Here</span>


I tried like this:

<a id="randomx" href="#">Text Here</a>
<script>
var image = new Array();
text[0] = "TEXT1";
text[1] = "TEXT2";
text[2] = "TEXT3";
text[3] = "TEXT4";
var size = text.length
var x = Math.floor(size * Math.random())

$('#randomx').attr('src', text[x]);
</script>



Answer Source

Here's a thought, try not using jQuery for every little thing.

 var el = document.getElementById("randomx");
var image = new Array();
image[0] = "TEXT1";
image[1] = "TEXT2";
image[2] = "TEXT3";
image[3] = "TEXT4";
var size = image.length
var x = Math.floor(size * Math.random())

el.src = image[x];       //set source
el.innerHTML = image[x]; //set link text
<a id="randomx" href="#"></a>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download