0

This should not be a difficult task, but for any reasons it keeps not working and I am not able to figure out why. Basically, I want to remove the paragraph with the class name "def" in the code below, but the getElementsByClassName method used in the script section seems unable to detect it, returning no elements:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script language="javascript">

    var elems = document.getElementsByClassName('def');
    alert(elems.length);
    while(elems[0]) {
        elems[0].parentNode.removeChild(elems[0]);
    }

</script>
</head>
<body>
<h1>This is a title</h1>
<p>Sample paragraph</p>
<p>Another sample paragraph</p>
<p class="def"><p id="definition">Text</p></p>
</body>
</html>

Anyone knows what is wrong? Thanks in advance!

BirdyBiker
  • 15
  • 1
  • You're trying to execute code before the elements exist. – j08691 Jun 22 '14 at 20:32
  • The script is executed before the document is completely read. Either put the script at the end of the document, or attach a listener and wait for the document to be ready. – deceze Jun 22 '14 at 20:32

1 Answers1

1
<script language="javascript">

    var elems = document.getElementsByClassName('def');
    alert(elems.length);
    while(elems[0]) {
        elems[0].parentNode.removeChild(elems[0]);
    }

</script>

Insert this after the HTML part.

Reason: The script is being executed before the HTML attributes are declared.

EDIT

Thanks to this comment

Or you could use a body onload function in JQuery

$(document).ready(function() {
// script here
});
Community
  • 1
  • 1
imbondbaby
  • 6,063
  • 3
  • 17
  • 51
  • or use a body onload function // jquery '$(document).ready(function() { /* code here*/});' construct – Manuel Arwed Schmidt Jun 22 '14 at 20:35
  • Correct! Added it to the answer with credits ofcourse – imbondbaby Jun 22 '14 at 20:38
  • Hi! I forgot to say that my intention is to use only native javascript functions. Now the getElementsByClassName method returns the desired element, but the script is still unable to remove the node :( any suggestions? – BirdyBiker Jun 22 '14 at 21:36