2017-01-31 5 views
1

Ich habe dieses HTML:Löschen aller HTML-Elemente innerhalb von div

<div class="row" id="conditional-one"> 
    <div class="large-12 columns"> 
      <h3><?php echo $arrayStage_rule_one_title?></h3> 
      <p> 
      <?php echo $arrayStage_rule_one_description?> 
      </p> 
      <ul style="list-style-type:disc; margin-left:10px;"> 
      <?php echo $arrayStage_rule_one_description_bullets?> 
      </ul> 
      <h3><?php echo $arrayStage_rule_one_bullets_title?></h3> 
      <br> 
      <ul style="list-style-type:disc; margin-left:10px;"> 
      <?php echo $html_rule_one_bullets?> 
      </ul> 
    </div> 
</div> 

und ich versuche, alle HTML-Elemente mit id="conditional-one" innerhalb des div zu löschen, wenn diese Bedingung erfüllt ist:

// select div by ID 
var conditionalOne = document.getElementById("conditional-one"); 

// Assign PHP strings to JavaScript variables 
var conditionalOneText = '<?php echo $place_bullet_one?>'; 

if (conditionalOneText !== "1" || conditionalOneText !== "2") { 
    conditionalOne.removeChild(conditionalOne.firstChild); 
} else { 
    // do nothing 
} 

Derzeit ConditionalOneText ist == 3 aber die divs innerhalb der conditional-one werden nicht gelöscht. Kann jemand mir helfen, alle HTML-Elemente innerhalb der conditional-one Div zu löschen, wenn die Bedingung erfüllt ist?

+0

Was wird gelöscht, wenn überhaupt? –

+1

Wenn Sie removeChild verwenden möchten, müssen Sie Ihre ersten Kindknoten wie folgt durchlaufen: while (conditionalOne.firstChild) { conditionalOne.removeChild (conditionalOne.firstChild); } – darron614

Antwort

4

Entfernen Sie einfach den gesamten Inhalt, indem Sie innerHTML auf "" setzen.

Auch wenn Sie wirklich nichts in Ihrem else Block tun, dann können Sie es einfach ganz entfernen, was mögliche Verwirrung in Ihrem Code beseitigt.

// select div by ID 
var conditionalOne = document.getElementById("conditional-one"); 

// Assign PHP strings to JavaScript variables 
var conditionalOneText = '<?php echo $place_bullet_one?>'; 

if (conditionalOneText !== "1" || conditionalOneText !== "2") { 
    // You can remove all nested HTML content simply by setting 
    // the innerHTML property of the element to "". 
    conditionalOne.innerHTML = ""; 
} 
+0

Ich wollte diese genaue Antwort Wort für Wort posten. – durbnpoisn

+1

Schön. Ich würde gerne wissen, warum die Version von OP nicht funktioniert hat. –

+0

Rechts. OP hätte angeben sollen, was passiert. –

Verwandte Themen