Why doesn't the link id? I need that when I clicked on the link href = "# 2" it worked focus on the link with id = 2. (I need to make an anchor)

If you remove the id, then the focus works, because it connects through the class. What is the reason?

<span class="notsun" tabindex="0">Так работает если нажать сюда</span><br> <a class="notsun" href="#2">Так не работает если нажать сюда url</a> <br> <p class="to-be-changed">Здесь просто текст</p> <a class="to-be-changed" id="2" href="#">А это ссылка с id 2 </a> .notsun:focus~ .to-be-changed { background: #000; color: red; } 
  • : focus in the first case works, because There is an attribute tabindex. In the second case, you need to put the selector: target. - NeedHate

3 answers 3

You can use jq

 $( ".notsun" ).click(function() { var attr = $(this).attr('href').slice(1);//Получаем значение из атрибута href и удаляем первый символ $('#'+attr).addClass('active');//Добавляем класс active setTimeout(function(){$('#'+attr).removeClass('active');},200);//Через timeout удаляем класс, для наглядности выбора }); 
 .to-be-changed.active { background: red; } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <span class="notsun" tabindex="0">Так работает если нажать сюда</span><br> <a class="notsun" href="#2">Так не работает если нажать сюда url</a><br> <a class="notsun" href="#3">Показать ссылку с ид 3</a><br> <a class="notsun" href="#4">Показать ссылку с ид 4</a><br> <br> <p class="to-be-changed">Здесь просто текст</p> <a class="to-be-changed" id="2" href="#">А это ссылка с id 2 </a><br> <a class="to-be-changed" id="3" href="#">Ссылка с ид 3</a><br> <a class="to-be-changed" id="4" href="#">Ссылка с ид 4</a><br> 
Clicking on the first link

enter image description here

2-link

enter image description here

3-link

enter image description here

  • Something does not work for you, because the effect I have is the same without it. - AndSol
  • What effect?, Put screenshots of the work to the answer - nicolaa
  • I seriously say opened even in a new window still does not work. but found a solution to another you can see below - AndSol

The identifier must begin with a Latin character. In your case, id is a digit that is invalid.

  • HTML 5 is allowed, but it does not solve the problem. - AndSol
  • one
    It works for me, I checked your code on jsfiddle jsfiddle.net/8jy97tx3 - boneskhv
  • my cheto doesn't work) - AndSol

In general, the solution was easier.

It was

 .notsun:focus~ .to-be-changed { background: #000; color: red; } 

has become

 .to-be-changed:focus { background: #000; color: red; }