jQuery(#id).val() vs. getElementById(#id).value

前端 未结 7 902
眼角桃花
眼角桃花 2020-12-01 16:02

I been searching but I can only find articles talking about one or the other. Which one is better?

I\'m making a small web app where performance is not a big concern

相关标签:
7条回答
  • 2020-12-01 16:37

    I've been looking into the performance differences with this recently and, slightly unsurprisingly, using vanilla JS to grab a value is faster than using jQuery. However, the fallbacks that jQuery provides to prevent errors, like what @Matt mentioned, is very useful. Therefore, I tend to opt for the best of both worlds.

    var $this = $(this),
        $val = this.value || $this.val();
    

    With that conditional statement, if this.value tries to throw an error, the code falls back to the jQuery .val() method.

    0 讨论(0)
提交回复
热议问题