Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why won't all the ids get changed though I selected all of them by using the # idname?

I am completely new to coding in general. I've started with the very basics of HTML, CSS and JavaScript.

I have two paragraphs:

<p id="title1">Change this</p>
<p id="title1"> Change this too! </p>

While the first one gets automatically changed by:

<script type="text/JavaScript">
    $('#title1').html('Changed!');
</script>

the second one doesn't. But shouldn't it? Since all #title1 are being changed?

I have the same problem for the onclick version. The first paragraph gets changed when clicking on it, the second doesn't.

<p id="title3" onclick="sayGoodbye();">Toggle this Hello - Goodbye</p>
<p id="title3" onclick="sayGoodbye();">Thing to click on</p>
<script type="text/javascript">
    function sayGoodbye(){
        $("#title3").html('Goodbye');
        $("#title3").click(function(){
            $("#title3").html("Hello again!");
            $("#title3").off("click");
        });
    }
</script>
like image 205
a tech kat Avatar asked Mar 11 '23 17:03

a tech kat


2 Answers

When you select an element by its id, only the first one gets selected because you're only supposed to use one id on one element! Each id should only ever be used once on a page!

If you need to get a bunch of elements together 'by' something, do it 'by class'.

$(".title1").html("Changed!");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="title1">Change this</p>
<p class="title1"> Change this too! </p>
like image 178
Samuel Reid Avatar answered Mar 13 '23 05:03

Samuel Reid


ID attribute has to be unique for each HTML tag. You can use class attribute to act on multiple tags.

like image 21
wscourge Avatar answered Mar 13 '23 07:03

wscourge