Jordan
Jordan

Reputation: 495

getElementsByTagName vs jQuery

What would the version of this be in jquery?

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

I need help converting this in order to fit into my $.get request:

$.get( 
    link, 
    function(data) {
        var res = $(data).find("pre").html();
        console.log(res);
    }
); 

Upvotes: 0

Views: 11763

Answers (4)

Abraham Hamidi
Abraham Hamidi

Reputation: 13809


The exact [JQuery equivalent] would be $('pre').eq(0).html(). The sortof-ish mix with non-JQuery would be $('pre')[0].innerHTML

How's it work?

$('pre') returns an Object with all elements with a tag name of pre

.eq(0) gets the first element in the array.

DEMO


Since you're getting the first item, $('pre').first().html() also works.

DEMO


Another thing that works would be just $('pre').html() (Credit to RobG)

DEMO


Please note that JQuery's html method is not identical to a browser's innerHTML property but it's the JQuery equivalent (Credit to RobG).


Upvotes: 5

Wayne
Wayne

Reputation: 60414

Simply specify the element name in the selector:

$("pre").html()

It's not necessary to explicitly select the first element. From the API docs:

If the selector expression matches more than one element, only the first match will have its HTML content returned

Upvotes: 0

user3105359
user3105359

Reputation:

If you only need one element, give the element and ID and pull it by ID

document.getElementById("ID")

Upvotes: 0

bearfriend
bearfriend

Reputation: 10421

Here it is in jQuery:

$('pre').first().html()

Upvotes: 2

Related Questions