1

I need some help in converting a javascrpipt function into jQuery. Below is my original JS code:

var text = document.getElementsByTagName("pre")[0].innerHTML;

After a little research on Stack I was able to come up with this equivalent:

var text = $(data).$('pre')[0].html();

Where data is the data I receive in a $.get request, like below.

$.get (
    mypage,
    function parse(data) {
        var raw = $(data).$('pre')[0].html();
    }
);

But that doesn't seem to work and i'm not very good with jQuery.

ztirom
  • 4,382
  • 3
  • 28
  • 39
Jordan
  • 445
  • 2
  • 10
  • 21

3 Answers3

1

Granted that data holds HTML, $(data).find('pre').eq(0).html() should do.

moonwave99
  • 21,957
  • 3
  • 43
  • 64
0

To get the first element with tag pre from data you can do the following in jQuery,

$('pre',data).eq(0).html();

http://api.jquery.com/jquery/#jQuery-selector-context

melc
  • 11,523
  • 3
  • 36
  • 41
0

The reason $(data).$('pre')[0].html(); doesn't work is that the [0] part extracts the first found element as a DOM element, not a jQuery object, so invoking .html() fails.

Others have already pointed out the solution. .eq(0) gets the first element as a jQuery object (per moonwave99 and melc's answers), and that's why you can then call .html() on it.

For further reading on the difference, see: jQuery object and DOM element

Community
  • 1
  • 1
Faust
  • 15,130
  • 9
  • 54
  • 111