2

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?

1
  • What do you get if you just try console.log($(myHTML).find('script').length) ? Commented May 10, 2011 at 17:30

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the info. If I use a regex to find the desired script tag, is there any way to ensure that I am not matching a script tag that is commented out (unlikely to happen, but possible)?
You can use a pre-processing regex to remove all commented out parts from your HTML before searching for the script.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.