a tech kat a tech kat - 1 year ago 62
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">

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

I have the same problem for the
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("Hello again!");

Answer Source

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'.

<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>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download