DevGav
DevGav

Reputation: 103

Select attribute of root element in jQuery

How do you select the attribute of a "root" level element in jQuery?

The following doesn't work (returns undefined):

jQuery(document).ready(function() {

    somehtml = "<a href='http://example.com'>An example</a>";
    theurl = jQuery('a',somehtml).attr('href');
    alert(theurl);

}

Any idea what I'm missing? I'm sure it's something obvious about root level elements ...

Many thanks in advance, Gav

Upvotes: 0

Views: 560

Answers (1)

Tower
Tower

Reputation: 102785

You could do:

jQuery(document).ready(function() {

    somehtml = "<a href='http://example.com'>An example</a>";
    theurl = $(somehtml).attr('href');
    alert(theurl);

});

What I did was to construct a jQuery object out of the HTML you had, and then directly access the attr()-function for that.

Upvotes: 3

Related Questions