user6002037
user6002037

Reputation:

apend text if class exists jQuery

I am trying to append text to a p element if a class exists. I would have been sure the below would work, but for some reason $(this) is being read differently to what I would have expected. Perhaps it is due to how the jQuery is set up.

I would like the p text to read Test This is gone

When I view $(this) in the console it is showing the object that the function is in.

I have html that looks like this

<div class="place-holder">
    <p class="place gone">Test</p>
</div>  

JQUERY

var app = app || {};
!function(){
    app.test = {
        init: function ( ) {
            if($('.place').hasClass( "gone" ) ){
               console.log($(this));
               $(this).append('This is gone');
            }
         }
    }

 $(document).ready(app.test.init);
}(jQuery);

Anyone have any ideas?

Upvotes: 1

Views: 170

Answers (2)

Blue
Blue

Reputation: 22911

You should just be able to do:

$('.place.gone').append('This is gone');

Also, if the input could possibly be malicious (Containing HTML), you should use document.createTextNode() to append:

$('.place.gone').append(document.createTextNode('This is gone'));

$(this) usually refers to the element that you're working with, but in this case, you're trying to get this from the init function (Which, since we don't know the caller, I'm unsure of what it could be.)

I think you're probably thinking about something like this:

$('.place').forEach(function() {
    //In this case, forEach assigns the element to the 'this' variable.
    if ( $(this).hasClass( "gone" ) ) {
        console.log($(this));
        $(this).append('This is gone');
    }
}

Upvotes: 2

charmeleon
charmeleon

Reputation: 2755

Unless the text you are appending should have HTML, you should use

$('.place.gone').append(document.createTextNode('Hello World'));

Upvotes: 0

Related Questions