$('#id') and getElementById

Hey,

I’m confused by how $(‘#id’) and getElementById work because I thought getting an element by id would only match once.

When I do this in jquery:


$('#click_event').click(function() {
  alert("Click event fired: " + $(this).text());

  return false;
});

<a href="#" id="click_event">Text 1</a>
<a href="#" id="click_event">Text 2</a>

It correctly shows the text. If it truely only matches once, then wouldn’t the second href not fire the event and take you wherever the href is taking you to?

When I see the source code onhttps://secure.elance.com/php/reg/main/buyersignup.php?emailSignupsId=555209
Payment method

How to create getElementById pop up using javascript.
Please tell me the simple source code. Because I am beginner.

Hi,

I just want to give you a little start with HTML and javascript.

Regarding w3c HTML attribute ID needs to be UNIQUE on whole page. That means when you use method document.getElementById(id) first element will be returned because there should be only one with that id. jQuery works same way. Why should they create functionality for invalid HTML.

But I know what is your need, so I will try to help you.

You can add another attribute to your element for example attribute “rel” and assign action to all elements with rel attribute and with specific value of that attribute. Example is below:


 $('a[rel=click]').each(function()
{
  $(this).click(function() { alert('Senad Meskin, www.wiseblog.info'); });
});

this will work for next html


<a href="#" rel="click" > Clicable</a>
<a href="#" rel="click" > Clicable</a>
<a href="#" > Clicable</a>

it wont work for a third link in HTML above.
But you need to execute this script when page is loaded, for example

$(document).ready(function(){ 
//put script from above
 });

I hope this will help you

When you start breaking the rules you can’t tell what will happen. With that code you could get five different outcomes from five different browsers if each implemented their code in a different way.

So basically what you are saying is that because I’m breaking valid HTML then the rule for matching once no longer applies?

It probably does just that in some browsers.

How any getElementById processing will work with that code is undefined since such a combination is not allowed in valid HTML and so browsers can do whatever they like with it.