1

How can I count the occurence of closing divs

$("body").html().match(/\/div/gi).length;

The Code above is not working as expected, although I escaped the slash. https://jsfiddle.net/zjqtpje4/1/

Tom Senner
  • 548
  • 1
  • 6
  • 21
  • Firstly, *never use Regex to parse HTML*. Secondly, the number of closing div tags will always be equal to the number of opening div tags as the browser will automatically insert any mismatching tags. Therefore you can just use `$('div').length` – Rory McCrossan Jul 07 '17 at 15:04
  • That's too bad because I want to have a function to discover open-divs. The Information with the browser aside: Shouldn't the match-function not be able to count the substring "" properly? – Tom Senner Jul 07 '17 at 15:05
  • In which case you would need to find a method of parsing the string without placing it in the DOM. Personally I'm not even sure if that's possible. – Rory McCrossan Jul 07 '17 at 15:06
  • You can check that easily in whatever editor you use. Just do a search for `
    – Huangism Jul 07 '17 at 15:07
  • I want an automatism for a big website, so copy paste into editors would be too time consuming. – Tom Senner Jul 07 '17 at 15:08
  • If the editor is of any worth it should fix mis-matching tag errors automatically. If the one you are using does not, find another one. – Rory McCrossan Jul 07 '17 at 15:08
  • It's the output of a contao website where admins can insert their own html, that's why I want to check the output. Also can you edit the fiddle so it finds the ONE closing div? – Tom Senner Jul 07 '17 at 15:11
  • I'm afraid not. As I mentioned then browser will fix the HTML, so there will always be 3 closing divs in your sample – Rory McCrossan Jul 07 '17 at 15:12

1 Answers1

0

Firstly, never use Regex to parse HTML.

Secondly, the number of closing div tags will always be equal to the number of opening div tags as the browser will automatically insert any mismatching tags.

You can see this behaviour in the console of the below snippet. Two closing </div> will be added to the code:

console.log($("body").html().match(/\/div/gi).length);
console.log($('body').html());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
    <div>
      <div></div>

The only way this could work is if you can work with the HTML as a string before it is placed in the DOM. This will prevent the HTML being corrected.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339