1

i'm finding a way to check if an HTML tag is empty (contains no text). first of all, i'm thinking about checking if the tag can contain text (which has closing tag).

it turns out:

<img>, <img/>, <br>, <br/>, <input> would return false

<div></div>, <p></p> would return true

please help, thanks in advance.

  • You should investigate the innerText property of an element. It will return an empty string if there is no human readable text, that sounds kind of like what you need correct? – djs Aug 14 '19 at 03:04
  • @Daniel.Schroeder sorry for unclear question. actually I want to find out empty elements to remove it and I don't want to remove `img`, `input` (which also have no innerText). – NGAN B. NGUYEN Aug 14 '19 at 03:22
  • What constitutes an empty element then? I suppose you could create a list of all the elements that you don't want to filter out, grab all the elements from the page, and then filter out only the elements that are not included in your list of 'empty' elements that you don't want to remove. Each element has a tagName property, where it returns the tag name as an uppercase string. Does that help at all? I have a pretty good idea of the code that would pull this off, but I think you may be able to figure it out if I'm correct in my reasoning above. – djs Aug 14 '19 at 03:34

2 Answers2

2

The W3 specifies some standard void elements as below link. It may give you some help.

Test if an element can contain text

qw20012
  • 89
  • 3
-3
console.log(document.getElementById("demo").innerHTML)

You can get html content inside element

Wang
  • 15
  • 1
  • 1
  • 6
  • 1
    thank you but my purpose is to check if a tag **can** contain text. with your code an empty `div` and an `img` would return the same. – NGAN B. NGUYEN Aug 14 '19 at 03:07