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
3 Answers
Reset to default 7You 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
版权声明:本文标题:javascript - JQuery - get attrtext from HTML string in a variable - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742407564a2469137.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论