Javascript / Jquery:从字符串中获取元素

时间:2014-10-28 11:23:14

标签: javascript jquery html

我需要从字符串中删除HTML元素。

如有任何建议,请在下面留言。

3 个答案:

答案 0 :(得分:2)

删除表似乎对我没用。你有没有等待dom加载,你可以使用$(document).ready()或window.onload

jsfiddle

window.onload = function () {
    var table = document.getElementById("fileTable");
    table.innerHTML = 'I removed the table';
    console.log(table);
}

答案 1 :(得分:2)

您可以使用substr()

直接删除表格
var myString = "smth <table>asdasdasd</table>smth else";
var firstPart =  myString.substr(0,myString.indexOf('<table>'));
var secondPart = myString.substr(myString.lastIndexOf('</table>')+8);
myString = firstPart + secondPart;

Fiddle

UPD 并且要从DOM中删除表,请使用jQuery方法:

$(document).ready(function(){
   $('#tableId').remove();
})

或纯粹的js:

var table = document.getElementById('tableId');
table.parentNode.removeChild(table);

答案 2 :(得分:1)

在阅读完全代码后,结果发现你缺少一个大括号:

   <script type="text/javascript">
      function privateComment(){
         var file = 0;
         var message = document.getElementById("commentPrivate").innerHTML;
         if(message.indexOf("contenteditable") > -1){
             var table = document.getElementById("fileTable");

             var type = table.getAttribute("type");
             var file_id = table.getAttribute("fileId");
             var taskId = table.getAttribute("taskId");
             table.innerHTML = '';
             var string = string +  '{"type": "' + type + '", "file_id": "' + file_id + '", "taskId": "' + taskId + '"}';
             var file = 1;
          } // <<< THIS IS NOT THE LAST BRACE
         var taskId = document.getElementById('form-task-title').getAttribute('showing');
         var button = document.getElementById("submit-private-comment");
         alert(message);
     }   //<<ADD THIS BRACE .

  </script>