首页 > 解决方案 > style a parameter from server side and append it to innerHTML

问题描述

I want to know if it's possible to style a string in a parameter and then append it to a innerHTML.

I'm getting a return message from the server side through a onSuccessHandler() (I'm working with a Google web app). I then get a element through getElementById() and add innerHTML and I want to add at the end the return message.

I know how to do that, that's simple document,getElementById('demo').innerHTML = Here is your function status:" + message;.

the issue is I want the two parts to have different colors. The first part I set with a style attribute in the tag with id="demo", but how can I style the message before appending it to the innerHTML.

Putting the first part in the actual tag is not an option because I use it for other alerts and want it to stay dynamic.

Below is my code

      //if "send fax" was successfull
    function fileUploaded(status) {
    
      //clears fields
    document.getElementById("myForm").reset();
    
      //displays success dialog box    
    document.getElementById('dialog1').innerHTML = "Fax Delivery Status: " + status;
    document.getElementById('dialog1').show();
                    setTimeout(delay, 3500);
    }
</script>
<body>

    <dialog id="dialog1"></dialog>

标签: html

解决方案


You could add 2 spans around the text with different classes. Or a less clean but more simple solution would be to add some inline style

change this:

document.getElementById('dialog1').innerHTML = "Fax Delivery Status: " + status;

to:

document.getElementById('dialog1').innerHTML = "<span style='color:white;'>Fax Delivery Status:</span> <span style='color:black;'>" + status + "<span>";

EDIT: As mentioned above the cleaner way is to assign classes and style the classes with css:

document.getElementById('dialog1').innerHTML = "<span class='color1'>Fax Delivery Status:</span> <span class='color2'>" + status + "<span>";

推荐阅读