将[object HTMLElement]格式化为变量字符串

时间:2017-05-27 07:31:19

标签: javascript jquery html

在此处使用此代码选择单击的元素,控制台记录除targetElement以外的任何内容产生[object HTMLElement]。是否有可能生成字符串结果的简单方法? Javascript或Jquery。

if (document.addEventListener ){
    document.addEventListener("click", function(event){
        var targetElement = event.target || event.srcElement;
        console.log(targetElement);
    });
} else if (document.attachEvent) {    
    document.attachEvent("onclick", function(){
        var targetElement = event.target || event.srcElement;
        console.log(targetElement);
    });
}

1 个答案:

答案 0 :(得分:0)

尝试targetElement.outerHTML



if (document.addEventListener ){
    document.addEventListener("click", function(event){
        var targetElement = event.target || event.srcElement;
        console.log(targetElement.outerHTML);
    });
} else if (document.attachEvent) {    
    document.attachEvent("onclick", function(){
        var targetElement = event.target || event.srcElement;
        console.log(targetElement.outerHTML);
    });
}




如果你想只获取那个元素(不是内部html)克隆那个节点并将innerHTML设置为空



 if (document.addEventListener ){
    document.addEventListener("click", function(event){
        var targetElement = event.target || event.srcElement;
         
           var newELement = targetElement.cloneNode();
         newELement.innerHTMl="";
         console.log(newELement.outerHTML);
     
    });
} else if (document.attachEvent) {    
    document.attachEvent("onclick", function(){
        var targetElement = event.target || event.srcElement;
         
           var newELement = targetElement.cloneNode();
         newELement.innerHTMl="";
         console.log(newELement.outerHTML);
    });
}