My javascript code doesn’t work, but when it is executed in the console it works

I have a problem, my javascript code does not work, I have an error in the console, but when I paste it in the console, it works perfectly. Somebody could explain me

if (document.getElementById('r1').checked){ 
    document.querySelector('.title-opa-dentals').classList.add('opacity')
};
.opacity{
    opacity: 1!important;
}
<div class="box-slider slides">
    <input type="radio" name="r" id="r1" checked>
    <input type="radio" name="r" id="r2">
    <input type="radio" name="r" id="r3">
    <div class="select-1"></div>
    <div class="select-2"></div>
    <div class="select-3"></div>
    <div class="navigation">
        <label for="r1" class="bar">
        <a class="title-opa-dentals">Dentals</a> 
        </label>
        <label for="r2" class="bar">
        <a class="title-opa-jewellers">Jewellers</a>
        </label>
        <label for="r3" class="bar">
        <a class="title-opa-industrials">Industrials</a>
        </label>
    </div>