I’m passing the entire HTML contents of an external web page to a javascript variable (“myHTML”). Next, I’m trying to determine whether two different tags with specific attributes exist within the myHTML variable. I’m looking for the existence of a certain <div> tag and <script> tag. I am able to identify the <div> tag:
alert($(myHTML).find('div[id^="myID"]').length)
The above code returns the correct count. However, I am unable to find the <script> tag (even though it does exist on the page / in the myHTML variable):
alert($(myHTML).find('script[src*="example.com"]').length)
The above code always returns zero, even though there is a <script> tag with a src attribute pointing to “…example.com/…”.
Can anyone explain why the first line of code works, while the second line fails? Is there any solution to this issue?
It was discussed before in here: jquery: Keep <script> tag after .find()
jQuery strips all script tags whenever you create a jQuery object from a string. The solution is to parse the string using regular expressions before you turn it into an object.