1

I have the following string:

<script src="https://sys.com/lerers/adkljrver?c=28dsfsd1&w=323434230&h=5424523420&ord=[timestamp]&z=0"></script>
<noscript>
<a href="https://ving-sys.com/server/asfdsfsdr.bs?cn=brd&pli=107dsfsd486sdfds231&Page=&Pos=1979577902" target="_blank">
<img src="https://bs.faf-sys.com/Serving/adServer.bs?c=8534&cn=displaying&pli=1073924861&Page=&Pos=77902" border=0 width=320 height=50></a>
</noscript>

My goal is to parse out the src, width, and height attributes without using regular expressions or any type of indexOf()/loop/If logic.

This parsing will happen within a browser, so native browser functionality or jQuery are acceptable to use.

I have tried this:

//myString is equal to the string above
var $jQueryObject = $('<div>' + myString + '</div>');
console.log($jQueryObject.find('img').attr('src'))

It returns undefined. I assume this has something to do with trying to parse elements within noscript and script tags. Any help returning the src, height, and width elements would be appreciated.

1
  • If you want to edit MY answer because you've changed your mind about the question, please edit your question too, because you made my answer wrong with respect to your question. Lord knowss how 3 other people approved such an edit Commented Aug 21, 2016 at 21:23

1 Answer 1

3

Using DOMParser would be the simplest method - please see the browser compatibility table in the link provided, specifically that this WONT work for IE9 or earlier

var parser = new DOMParser(),
    ns = document.querySelector('noscript'),
    doc = parser.parseFromString(ns.textContent, 'text/html'),
    img = doc.querySelector('img');
console.log(img.width);
console.log(img.height);
console.log(img.src);

Note: you can do the above like this to impress the girls:

var img = (new DOMParser()).parseFromString(document.querySelector('noscript').textContent, 'text/html').querySelector('img');
console.log(img.width);
console.log(img.height);
console.log(img.src);

In the case of IE8/IE9, if you must support them, you can do something like

var div = document.createElement('div');
div.innerHTML = document.querySelector('noscript').textContent;
var img = div.querySelector('img');
console.log(img.width);
console.log(img.height);
console.log(img.src);

But please be aware, the image will be fetched using this code

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

Comments

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.