DEV Community

n350071🇯🇵
n350071🇯🇵

Posted on • Edited on

1 1

My Javascript note ( include JQuery )

Selector

Find by multi classes

<element class="a b">
Enter fullscreen mode Exit fullscreen mode
$('.a.b')
$('.b.a')
Enter fullscreen mode Exit fullscreen mode

Find the last element

<div id='hello'>
  <p class='world'>a</p/>
  <p class='world'>b</p/>
  <p class='world'>c</p/>
</div>
Enter fullscreen mode Exit fullscreen mode
$(#hello).find('.world:last')
// => c
Enter fullscreen mode Exit fullscreen mode

form

metaprogramming like form submit

Good for grecapcha call-back v2 workaround.

onSubmit = function(){
  const formName = $('.agreement').find('input').attr('name').split('[')[0]
  $(`form[id*=${formName}]`)submit();
}
Enter fullscreen mode Exit fullscreen mode

stop event bubbling

event.preventDefault();
Enter fullscreen mode Exit fullscreen mode

Manipulation

add/append a element

It appends hidden input that gives a param 'force_invalid'.

<form class="my-form">
</form>
Enter fullscreen mode Exit fullscreen mode
function invalid_submit(document) {
  $(document).append("<input name='force_invalid' value='1' type='hidden'></input>" );
  $(document).closest('form').submit();
}
Enter fullscreen mode Exit fullscreen mode

set a value

$('input[name="some_request[policy_agreement]"]').val("0");
Enter fullscreen mode Exit fullscreen mode

if checkbox is checked, open a panel

$.each($(".checkbox"), function(){
    // scope of 'this' is the checkbox
    if($(this).is(":checked")){
        $(this).closest("div").slideToggle("fast");
    }
});
Enter fullscreen mode Exit fullscreen mode

Tips

expression substitution inside a string literal. (式展開)

${} inside the backquote (`) substitute the expression.

const formName = 'my-form'
$(`form[id*=${formName}]`)submit();

$('form[id*=`formName`]').submit(); // ❌doesn't work
$('form[id*=formName]').submit();   // ❌doesn't work
Enter fullscreen mode Exit fullscreen mode

Uncaught Syntaxerror: Unexpected token u

It's same as console.log(JSON.parse(undefined));.
JSON.parse is actually undefined.

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series