apwnn
apwnn

Reputation: 87

How to access the first child of an element in jquery

I have a click event which executes code inside the function. I need to use $(this) because I need to refer with that particular element I clicked and not anything else.

Is there a way to access to the first child of the element using $(this)?
This is my code:

$('#songs_box tr td.playtitle').click(function () {
    var tr = $(this).parent();

    if(tr.hasClass("active")){
        if (audio.paused) {
            $(this).firstChild.innerHTML = '<i class="fas fa-pause"></i>';
            audio.play();
        } else {
            $(this).firstChild.innerHTML = '<i class="fas fa-play"></i>';
            audio.pause();
        }
    } else {
        audio.pause();
        initAudio(tr);
        audio.play();
    }
});

Upvotes: 1

Views: 82

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337713

firstChild and innerHTML are properties of a native JS Element object, not a jQuery object, which is what $(this) creates.

To fix this use children().first().html() instead:

$(this).children().first().html('<i class="fas fa-pause"></i>');

Alternatively you could just toggle the class on the i directly:

$(this).find('i').toggleClass('fa-pause fa-play');

In any case I'd suggest having a scan through the jQuery documentation so you get an understanding of the methods available. The functionality of the vast majority of them can be understood just from their names.

Upvotes: 2

Related Questions