Search code examples
javascriptmethodssplitstyles

javascript style is not working on splited strings


When i split two words using split() method, i can't style it with pure javasript. My intention is to change color of second word. Is anyone knows the solution. The code is as follows. Thanks in advance.

HTML:

<p id="demo">Better Choice</p>

Javascript:

let a = document.getElementById('demo').innerHTML;
let b = a.split(" ");
let c = b[1];
c.style.color="red"; // this is not working

Solution

  • C at the moment is just the work Choice it is not an HTML element so you cannot add style. If you want to add style you need to turn it into an element and then style it.

    let a = document.getElementById('demo').innerHTML;
    let b = a.split(" ");
    let c = document.getElementById('demo').innerHTML = b[0] + " <span style='color:red'>" + b[1]+ "</span>";
    

    Once you do the a.split(" ") you lose access to the element itself so you need to get it again for C.

    You could also do this

    let a = document.getElementById('demo');
    let b = a.innerHTML.split(" ");
    let c = a.innerHTML = b[0] + " <span style='color:red'>" + b[1]+ "</span>";
    

    Also if you want the color red exposed to edit dynamically you could use String Literals like this.

    let a = document.getElementById('demo');
    let b = a.innerHTML.split(" ");
    let color = "red";
    let c = a.innerHTML = `${b[0]} <span style='color:${color}'>${b[1]}</span>`;
    <p id="demo">Better Choice</p>