jQuery - selectors on a html string

后端 未结 4 742
野的像风
野的像风 2020-12-14 15:36

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:

asd

        
相关标签:
4条回答
  • 2020-12-14 15:59

    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).

    0 讨论(0)
  • 2020-12-14 16:01

    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>

    0 讨论(0)
  • 2020-12-14 16:03

    I have a response that is of the form:

    <div>...
    </div>
    
    <div>...
    </div>
    
    <div>...
    </div>
    

    And @minitech 's method resulted in an array of HTML nodes in which the selector didn't work.

    So I tried this and it worked out nice:

    $.ajax({
        url:
        success: function($data) {
             var $parsed_data = $('<div/>').append($data);
             var found = $parsed_data.find(".Selector");
             ...
        }
    });
    
    0 讨论(0)
  • 2020-12-14 16:11

    Try:

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

    or:

    console.log($('.test', '<table><td class="test">asd</td><td class="second">fgh</td><td class="last">jkl</td></table>').html());
    
    0 讨论(0)
提交回复
热议问题