简体   繁体   中英

Using Javascript to check if an HTML snippet is visually empty

I need to process some HTML snippet embedded as email content, in a node.js server. The goal is to check if the snippet visually appears empty, and if so, display some placeholder text.

For example, this snippet is considered visually empty:

<div><br></div><div><includetail><!--<![endif]--></includetail></div>

since it will appear empty when rendered in browser, while this snippet is considered visually non-empty:

<div><br></div><div>Hello!</div>

since Hello! will appear when the snippet is rendered in browser.

How to implement such a function to return visual emptiness for an HTML snippet?

I wouldn't run JavaScript in an email, its really badly supported.

http://en.wikipedia.org/wiki/Comparison_of_e-mail_clients

In general a jQuery solution would be something like the following

$("*").empty().text("placeholder here");

A pure JavaScript solution would be

var list = document.getElementsByTagName('*');
for (var i = 0; i < list.length; i++) {
  if (list[i].innerHtml === "") {
    list[i].innerHtml = "placeholder here"
  }
}

Edit: Since you stated in a comment that you're going to run this in node, have a look at cheerio for a jQuery node replacement. https://github.com/cheeriojs/cheerio

My code will work fine after you pass it through cheerio

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