开发者

JQuery: Select text between closed tags

开发者 https://www.devze.com 2023-03-30 10:25 出处:网络
Similar questions have been asked but not quite similar enough! Given this structure: <p class=\"text\">

Similar questions have been asked but not quite similar enough!

Given this structure:

<p class="text"> <b>1</b>this is point one<b>2</b>this is point two<b>3</b> </p>

How would I select the text between the closed tags? ie "this is point one".

The content is fed back via a JSON call so I can't do much with the structure they're gi开发者_如何学Goving me.

Thanks!


can replace your <b>#</b> to something easier to split on then iterate over the results

example jsfiddle

jQuery:

var points = $('.text').html().replace(/<b>.<\/b>/g, ',').split(','),
    $results = $('#results');
for (var i in points) {
    if ($.trim(points[i]).length > 0) {
        $results.html($results.html() + points[i] + "<br />");
    }
}


If you need access to several of the text nodes, you can extract it all into an array using:

var data = $(".text").contents().filter(function() {
    return this.nodeType == Node.TEXT_NODE && !this.nodeValue.match(/^\s*$/);
}).toArray();

You can now access "this is point one" using data[0].nodeValue and "this is point two" using data[1].nodeValue.

Working fiddle: http://jsfiddle.net/jHhFS/

Note: The additional condition (!this.nodeValue.match(/^\s*$/)) filters out text nodes that contain only whitespaces.


you can get to that value using .contents(). In your case this would work:

alert($(".text").contents().eq(2).text())


Here's a potential solution:

var nodes = $('p.text')[0].childNodes;
var results = [];

for (var i = 0; i < nodes.length; i++) {
    if (nodes[i].nodeType == Node.TEXT_NODE) {
        // support older browsers that do not have textContent
        var text = nodes[i].textContent || nodes[i].innerText;
        if ($.trim(text).length > 0) {   // optional - push non-empty strings
            results.push(text);
        }
    }
}
//console.log(results);

Demo: http://jsfiddle.net/mrchief/3L8Ze/1/


You could try -

console.log($('p').contents().filter(function() {
    return this.nodeType == Node.TEXT_NODE;
}));

This is taken from - How do I select text nodes with jQuery?. As stated in the linked question, the solution won't work with IE7, but there is a workaround detailed in the linked question.

Working demo - http://jsfiddle.net/E53HU/1/

0

精彩评论

暂无评论...
验证码 换一张
取 消