开发者

remove div without an id tag

I need a solution to remove a div without an ID tag in JavaScript only. The div looks like this <div align="center">.

Here is the full structur开发者_运维问答e.

<tr id="-1">
  <td class="stxt">
    <div align="center">
    </div>
  </td>
</tr>


You need to work out how to get a reference to it, once you've done that, you can remove it using:

div.parentNode.removeChild(div);

Of course the align attribute has been deprecated, but anyway, you can find the divs with align="center" using:

var divs = document.getElementsByTagName('div');
var div;
var i = divs.length;

while (i--) {
  div = divs[i];

  if (div.getAttribute('align') == 'center') {
    div.parentNode.removeChild(div);
  }
}

Which will remove every div in the document that has align="center".

Note that the object returned by getElementsByTagName is a NodeList. If you iterate over it from 0 and remove nodes, they are removed from the live list so you will skip the node following the one you remove and you will attempt to access no existant nodes at the end. Going over the list backwards avoids these pitfalls. An alternative is to turn the NodeList into an array, but that's somewhat inefficient.

Edit

Since you edited the question, here's an update answer.

You can get a reference to the TR using getElementById:

var root = document.getElementById('-1');

Now you can go down the DOM:

var cell = root.cells[0]; // First cell in the row
var div = cell.getElementsByTagName('div')[0]; // first div
cell.removeChild(div);

Which is specific to the structure you've posted.


If you can just remove the content, you can use:

var all = document.getElementsByTagName("div");
for(i=0; i < all.length; i++) {
    all[i].innerHTML = ""
}

See http://jsfiddle.net/7KVkC/


You need some way to make this div tag unique. There is another javascipt function called getElementsByTagName that you can use to get an array of all of the div tags. You can then use the DOM to check whether that div tag has the property of align="center".

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜