开发者

Javascript Element to string

开发者 https://www.devze.com 2023-02-19 21:49 出处:网络
I am creating div element like below and inserting some html cont开发者_如何学JAVAent inside div and innerText.

I am creating div element like below and inserting some html cont开发者_如何学JAVAent inside div and innerText.

var creatediv=document.createElement("DIV");
var html="<div align="left"><a id="test" >test</a></div>";
creatediv.innerHTML=html;
creatediv.innerText="testing";

Now my question is how to retrieve the updated html variable here.

Thanks,

Raj


You should be able to retrieve the current HTML from creatediv using creatediv.innerHTML.

var creatediv=document.createElement("DIV");
var html="<div align=\"left\"><a id=\"test\" >test</a></div>";
creatediv.innerHTML=html;
creatediv.innerText="testing";
html = creatediv.innerHTML;


You just overwritten your innerHTML at line 4. So your innerHTML value in question will be equal to 'testing' string, given your DOM implementation supports non-standard property innerText or equal to html variable value otherwise.


Append the creatediv to dom tree first, then retrieve by function getElementById.

document.append(creatediv);


Well, this is a function that converts value to a string if it's not one. An empty string is returned for null or undefined value:

function baseToString(value) {
    if (typeof value == 'string') {
        return value;
    }
    return value == null ? '' : value + '';
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号