I have this long string and I want a part of it transformed into white colour using only JavaScript.
Example 1:
var string = document.getElementById("subtitle").innerHTML; //returns the string
var i = string.indexOf("("); //returns 80
var j = string.indexOf(")"); //return 93
Example 2: I can get the wanted text but I don't know how to change it white
var string = document.getElementById("subtitle").innerHTML; //returns the string
var i = string.indexOf("(");
var j = string.substring(i, string.indexOf(")")+1); //return the exact string I want to paint white
//j.paintWhite(); how?
I would like to paint all the characters between positions 80 and 93 (or selected as shown in example #2) white. How can I do it?
You need to create an html container for that text where you can specify a style attribute.
also, do not use the variable name string
as it is reserved to the language
In order to do that, I would recommend using jQuery, as it is a bit easier.
But if you don't want to, you can do:
var text = document.getElementById("subtitle").innerHTML;
var cut = text.split("(");
var cut2 = cut[1].split(")");
var colored = cut[0] + '<span style="color:#fff;">('+cut2[0]+')</span>'+cut2[1];
document.getElementById("subtitle").innerHTML = colored;
if you assume "transformed into white colour" is doing
<span style="color:#fff">MY_TEXT_HERE</span>
then you could try the following with arrays:
var string = document.getElementById("subtitle").innerHTML;
var arr1 = string.split('(');
var arr2 = arr1[1].split(')');
var finalString = arr1[0] + '<span style="color:#fff">' + arr2[0] + '</span>' + arr2[1];
You must modify the inner Html of the element so it has a text element nested with a defind style.
var element = document.getElementById("subtitle");
var htmlText = element.innerHTML;
var i = htmlText.indexOf("(");
var j = htmlText.indexOf(")")+1;
var redText = htmlText.substring(i, j);
element.innerHTML = htmlText.substring(0,i)+"<a style='color:red;'>"+redText+"</a>"+htmlText.substring(j);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.