简体   繁体   中英

How to replace empty html tags with javascript?

I have some code that I want to insert or replace with a desired set of code if it is blank. Any direction in Javascript or jQuery?

If html code equals this:

<td id="Display1234"></td>

change to:

<td id="Display1234">
    <select name="ShippingSpeedChoice" onchange="RecalcShipping(this);" style="">
      <option value="101" selected="">Free</option>
    </select>
</td>

You would need to start by getting all the elements on the page (as I'm assuming you don't know which ones are empty).

// need to use Array.prototype.slice because getElementsByTagName
// returns an HTMLCollection and not an Array
var allElementsArray = Array.prototype.slice.call(document.body.getElementsByTagName('*'));

var emptyElements = allElementsArray.filter(function(element) {
  return !element.innerHTML; // returns true for all empty elements
});

I don't know what data to insert but you can then loop through the emptyElements array;

emptyElements.forEach(function(element) {
  element.innerHTML = 'some content or HTML';
});

Try using the following for a pure JavaScript solution:

 var td = document.getElementById('Display1234'); if (td.innerHTML.trim() == ""){ // Creating the select element var select = document.createElement('select'); select.setAttribute('name', 'ShippingSpeedChoice'); select.setAttribute('onchange', 'RecalcShipping(this);'); select.setAttribute('style', ''); // Creating the option element var option = document.createElement('option'); option.innerText = "Free"; option.setAttribute('value', '101'); option.setAttribute('selected', ''); // Appending elements to td element select.appendChild(option); td.appendChild(select); } 
 <table> <td id="Display1234"></td> </table> 

$('#Display1234').html('your html');
// if the div is empty
if($("#Display1234").html()===""){
    // create a a <select> element
    var $sel = $('<select name="ShippingSpeedChoice" onchange="RecalcShipping(this);" style="">');
    // add an option to the select element
    $sel.append('<option value="101" selected="">Free</option>');
    // add the select element to the div.
    $sel.appendTo("#Display1234");
}

 window.addEventListener("DOMContentLoaded", function(){ var theCell = document.getElementById("Display1234"); if(theCell.textContent.trim() === ""){ theCell.innerHTML = '<select name="ShippingSpeedChoice" onchange="RecalcShipping(this);" style=""> <option value="101" selected="">Free</option></select>' } }); 
 <table> <tr> <td id="Display1234"></td> <td id="other1">something</td> <td id="other2">something else</td> </tr> </table> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM