DEV Community

Discussion on: Re-implementing jQuery methods in the HTMLElement prototype

Collapse
 
fernandosavio profile image
Fernando Sávio

How would you simulate jQuery $('#el').html(''); ?

Thread Thread
 
jochemstoel profile image
Jochem Stoel

You can literally use my example already provided in the post:

window.$ = (query, ctx = document) => ctx.querySelector(query)
window.$$ = (query, ctx = document) => ctx.querySelectorAll(query)

HTMLElement.prototype.html = function (string) {
    if (!string)
        return this.innerHTML
    this.innerHTML = string
    return this
}

then

$('#el').html('')
Thread Thread
 
fernandosavio profile image
Fernando Sávio • Edited

That wouldn't work because '' would evalute to false and in your code it would be the same as $('#el').html().

Check it running: codepen.io/fernandosavio/pen/qLWeWV

Thread Thread
 
jochemstoel profile image
Jochem Stoel

Well whatta ya know. You are right.
Change the line

if (!string)

into this

if (typeof string == 'undefined')

so that you get

window.$ = (query, ctx = document) => ctx.querySelector(query)
window.$$ = (query, ctx = document) => ctx.querySelectorAll(query)

HTMLElement.prototype.html = function (string) {
    if (typeof string == 'undefined')
        return this.innerHTML
    this.innerHTML = string
    return this
}

$('#test').html('');

codepen.io/jochemstoel/pen/OrJLbR

You can also replace it with

if(typeof string != 'string')

or even

if(string == undefined)