a tech kat a tech kat - 1 month ago 7
jQuery Question

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>

Answer

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>