Henrik Petterson
Henrik Petterson

Reputation: 7094

jQuery(this) target isn't finding element

How come this works:

jQuery(this).closest("li").find("p").text();

But when I have it inside a function, it doesn't work:

jQuery.each(words, function(i, v) {
    jQuery(this).closest("li").find("p").text();
});

Do I need to pass this through the function?

Full Code:

jQuery(document).ready(function() {
    jQuery('.js-trigger-editb').bind("mouseup", function() {

        // find the p tag that contains the content and split it
        var words = jQuery(this).closest("li").find("p").text().split(" ");

        // wrap words in p tag into span tags
        jQuery.each(words, function(i, v) {
            jQuery(this).closest("li").find("p").append(jQuery("<span>").text(v));
        });

    });
});

Upvotes: 1

Views: 75

Answers (3)

Roman Granovsky
Roman Granovsky

Reputation: 171

I'd like to suggest to save the link to the found "p" element not to search it each time.

    var p = jQuery(this).closest("li").find("p");
    var words = p.text().split(" ");

    jQuery.each(words, function(i, v) {
        p.append(jQuery("<span>").text(v));
    });

Upvotes: 3

laaposto
laaposto

Reputation: 12213

jQuery(this) is a reference to the DOM element of invocation. So it is different element when you call it inside jQuery('.js-trigger-editb').bind("mouseup", function() {}); and jQuery.each(words, function(i, v) {});.

Try to save it outside the .each.

Try:

var $this= jQuery(this);
jQuery.each(words, function(i, v) {
    $this.closest("li").find("p").append(jQuery("<span>").text(v));
});

Upvotes: 1

techfoobar
techfoobar

Reputation: 66663

Like you have mentioned in the question, the value of this inside the function is the problem. Inside the callback for .each(), the value of this is the current item in the array being iterated.

Something like this should work:

var elem = this; // here, 'this' is the element. Store it.

jQuery.each(words, function(i, v) {

    // use the stored element handle from 'elem'
    jQuery(elem).closest("li").find("p").append(jQuery("<span>").text(v));
});

Upvotes: 1

Related Questions