admin管理员组

文章数量:1336755

I have a HTML string that I'm passing through a function and I want to be able to perform Jquery methods on that variable from inside the function - such as .attr('href') or .text(). I'm sure there is a simple solution for this and something more elegant then temporarily appending the DOM.

HTML

<div class="here"></div>

Javascript

link = '<a href="">Google</a>';

// This works
$('.here').html(link);
works = $('.here').text();
console.log(works);

// This doesn't
not = link.text();
console.log(not);

/

I have a HTML string that I'm passing through a function and I want to be able to perform Jquery methods on that variable from inside the function - such as .attr('href') or .text(). I'm sure there is a simple solution for this and something more elegant then temporarily appending the DOM.

HTML

<div class="here"></div>

Javascript

link = '<a href="http://www.google.">Google</a>';

// This works
$('.here').html(link);
works = $('.here').text();
console.log(works);

// This doesn't
not = link.text();
console.log(not);

http://jsfiddle/dfgYK/

Share Improve this question asked May 8, 2013 at 20:26 Ryan GrushRyan Grush 2,1384 gold badges43 silver badges66 bronze badges 1
  • 3 Because String object doesn't have text method. – Ram Commented May 8, 2013 at 20:28
Add a ment  | 

3 Answers 3

Reset to default 7

You need to create a jQuery object from link in order to use jQuery methods on it. Try:

not = $(link).text();

DEMO: http://jsfiddle/dfgYK/1/

Depending on what you're doing with link, it might be beneficial to do this earlier in your code so that you can just use something like:

var $link = $(link);
console.log(link.text());

You can make a jQuery object that is not part of the DOM by passing a string in:

link = $('<a href="http://www.google.">Google</a>');

Then, jQuery methods will work on it:

var text = link.text();

Create the link with jQuery instead:

var link = $('<a />', {
    href: "http://www.google.",
    text: "Google"
});

Then you can access it's properties with link.text() like you wanted.

本文标签: javascriptJQueryget attrtext from HTML string in a variableStack Overflow