I have input value of HTML text with html tags inside this value like below
HTML
<input type="hidden" value="<!DOCTYPE html><html amp4email><head></head><body>...Content...</body></html>" id="ampHtml" />
Attempted Script:
var __amp_content = $("#ampHtml").val();
var __attr = jQuery(__amp_content).find('html').attr('amp4email');
if (typeof __attr !== 'undefined' && __attr !== false) {
alert('Fail');
} else {
alert('Success...');
}
How can I show alert based on:
- if html has amp4email show alert as Success
- Else show alert as Fail
CodePudding user response:
It looks like jQuery is including only the contents of the <body>
tag after parsing, which in this case is only a text node. The info you want isn't in the resulting object.
One option would be to use DOMParser instead. There's no need for a big library like jQuery for something like this anyway.
const ampContent = document.querySelector('#ampHtml').value;
const doc = new DOMParser().parseFromString(ampContent, 'text/html');
const attribute = doc.documentElement.getAttribute('amp4email');
console.log('Has attribute:', attribute !== null);
<input type="hidden" value="<!DOCTYPE html><html amp4email><head></head><body>...Content...</body></html>" id="ampHtml" />