Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - selectors on a html string

I am going to get a element from a html-string with jQuery, but I always get an undefined in my console. My String is:

<td class="test">asd</td><td class="second">fgh</td><td class="last">jkl</td> 

and I want to get the td.test.

I've tested:

console.log($('.test', '<td class="test">asd</td><td class="second">fgh</td><td class="last">jkl</td>').innerHTML); console.log($('.test', '<td class="test">asd</td><td class="second">fgh</td><td class="last">jkl</td>').html()); console.log($('.test', '<td class="test">asd</td><td class="second">fgh</td><td class="last">jkl</td>').first().innerHTML); 

and some more, but nothing works :/

Does anyone know a solution for my problem?

like image 406
MaxiNet Avatar asked Mar 04 '12 00:03

MaxiNet


2 Answers

First, use jQuery.parseHTML to parse the HTML into an array of elements; then you’ll be able to convert it to a jQuery collection and use filter to restrict the collection to elements matching a selector.

var html =      '<td class="test">asd</td>' +      '<td class="second">fgh</td>' +      '<td class="last">jkl</td>';    var text = $($.parseHTML(html)).filter('.test').text();    console.log(text);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
like image 100
Ry- Avatar answered Oct 02 '22 12:10

Ry-


You can't use jQuery selectors on a collection of nodes like this. You can wrap in a single node to work around this, so just add e.g. a wrapping <tr> node.

var htmlBits = '<tr>'   + '<td class="test">asd</td><td class="second">fgh</td><td class="last">jkl</td>'   + '</tr>'; 

And then it will work:

console.log($('.test', htmlBits).text()); // outputs 'asd' 

JSFiddle (remember to view the console to see the log).

like image 36
Charles Goodwin Avatar answered Oct 02 '22 12:10

Charles Goodwin