All elements are changed on click, not just on the target.

I just play with some basic jQuery and something weird is happening. I have two elements on the page: h1 heading and general link. When I click the link, I would like the text to change to “This text has now changed” and this happens, but then either the button disappears, or a new h1 is created with the same text “this text has not been changed”, or the button itself turns into h1. I'm not sure, but here is my code:

HTML:

<html> <head> <title></title> <link rel="stylesheet" type="text/css" href="css/main.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script> <script src="js/main.js"></script> </head> <body> <h1>This element should change.<h1> <a href="#" class="myLink">Click Me</a><br> </body> </html> 

JQUERY:

 $(document).ready(function() { $(".myLink").click(function() { // this is a convenience method that targets the same elements above just in a quicker fashion. $("h1").html("This text has now changed."); }); }); 

Image Before Clicking:

enter image description here

Image after:

enter image description here

Also, when I added the fading method, everything disappears again, and not just the target element "h1".

Any advice is welcome, as always. Thanks.

+5
source share
3 answers

You have two opening <h1> tags (the second is missing / .)

 <h1>This element should change.<h1> ^here 
+7
source

It looks like you have two start tags. EG:

 <h1>Heading 1<h1> 

Try changing the second tag to the end tag. EG:

 <h1>Heading 1</h1> ^ 
+5
source

Your h1 tag is not closed. You have 2 opening tags, and by default your link is contained in the second opening tag, so it changes this html

+4
source

Source: https://habr.com/ru/post/1241761/


All Articles