Most efficient/quickest way to add a number to a DOM element jquery

Viewed 46

I am learning the basics of jQuery and was testing out what I knew, I tried adding 1 to the text of a DOM element (<span>) that stores a number. The number in the <span> is increased by 1 successfully, however I feel that the way I am updating the element isn't the best way as it seems that I need to call the same jQuery function twice (see code below).

Would anyone be able to suggest a better practice?

HTML

<button onclick="foo('a')">
    <span id="a">0</span> liked this
</button>

JS(jQuery)

function foo(elementId){
    $('#' + elementId).text(parseInt($('#' + elementId).text()) + 1);
}

Thank you :-)

3 Answers

Avoid inline event handlers is the first thing to do. The once you setup your event handler you can reference the element via this:

$('button').click(function() {
  $(this).find('span').text( parseInt($(this).find('span').text()) + 1 );
})

The way you do it is kind of ok but I would try to avoid storing state in a text node.

There are couple of ways, I'm going to suggest jQuery's .data.

<button onclick="handleClick" data-count="0">
    <span id="a">0</span> liked this
</button>
function handleClick() {
  var $this = $(this);
  var count = $this.data('count');

  // update state
  $this.data('count', count + 1);
  // update view
  $this.find('#a').text(count + 1);
}

Yes, that's also true that you don't have to use inline handlers.

Because you have only one element inside button (i.e.: span) I would suggest a different approach without using jQuery. Disavantages:

  • inline event handler
  • i assume there is only one child

function foo(ele){
    ele.children[0].textContent = parseInt(ele.textContent) + 1;
}
<button onclick="foo(this)">
    <span id="a">0</span> liked this
</button>

As per your comment the code is:

document.querySelector('button').addEventListener('click', function(e) {
  this.children[0].textContent = parseInt(this.textContent) + 1;
});
<button id='b'>
    <span id="a">0</span> liked this
</button>

Related