This problem has been persistent and a real pain in the neck for the last few years.
I first ran across this example when implementing schema (itemprop, etc) within my code. I would be hacking away in WordPress HTML editor (text tab) for hours upon end. At some point I would switch to the visual editor (visual tab) and poof! All my work was deleted!
This happened again tonight as I was learning how to do inline SVG shapes in WordPress and all my work was deleted when switching to WordPress.
Eventually I found a solution that basically tells WordPress not to strip out any code when switching from the visual editor to the text editor. It basically tells WordPress to allow all elements inside the visual editor.
You can view / download the solution here.
You will have to paste the above code into your theme’s functions.php file at the very bottom.
It would probably be a good idea to do this insider of a child theme but I like to live on the edge.
I was able to confirm in 3 different themes that the above code works. Please note that this may not work 100% of the time and to always backup your work!
Being that WordPress uses the tried and true TinyMCE editor it is forced to conform to their standards. One of the things that TinyMCE does is defines “valid elements” within their own code. If your code does not match these elements, it will get stripped out when “saved” or in this case when you switch from visual mode to text mode.
Alternative solution: force text editor on certain pages
While doing some research, I ran across this solution with accompanying code snippets that basically tells WordPress “force the text editor, only on these pages or posts.”
I was able to confirm that this does indeed work, and is probably a safer solution than the above.