views:

68

answers:

5

i want to know is there any way to identify an html element by its "id"? if so than how can i call another html element e.g html table by is id all this using java script.

<a id="a" class="menuheader" >New Arrivals</a>
<a id="a1" class="menuheader" >Concepts</a>

i want JavaScript to identify the id of the above two elements and upon identifying the id call another html element i.e a table

+2  A: 

I am not quite sure what you want.

  • To get an element by its ID, you can use document.getElementById(id).

  • To get the ID of an element, you need a reference to the element and access the id property: element.id.

Felix Kling
how to set reference to the element? Can you please explain to me how to retrieve an id of an element in java script.
@user243680: *Can you please explain to me how to retrieve an id of an element in java script.* That is second point in my list. *how to set reference to the element?* That is the first point. There are various ways to get references. Check out the `document.getElementsBy*` methods. Once you have reference, you can also access its children and so forth. I suggest to read http://www.w3schools.com/jsref/default.asp for a start.
Felix Kling
+1  A: 

To access an object in your DOM by its id you can use document.getElementById("...").

To enumerate the children of a container:

for (var i in containerElement.childNodes)
    var elementId = containerElement.childNodes[i].id;
BlueCode
`foreach` is not a JS construct. You want `for` and `containerElement [i]`. In any case, I prefer `for (var i = 0; i < containerElement.childNodes.length; ++i) { var id = containerElement.childNodes [i].id; }`
trinithis
Thank you, I've corrected my code.
BlueCode
A: 

You could always use the jQuery JavaScript framework, which IMO is way better than plain old JavaScript for the most part. In jQuery you would just pass the eleent's ID you want to select (prevexied by the hash symbol to identify the selector is an ID) as a string to the jQuery function. Then , your action would follow a period after the selector

jQuery('#a').actionGoesHere()

But you would more commonly call the jQuery function by it's alias, the dollar sign:

$('#a').actionGoesHere()

Not so sure by what your second part of the question means, so if you clear that up a little, I'd be glad to help.

BOSS
A: 

I think something like this is what you are trying to do if I understand you correctly. The first one is if you are using named anchors to call your tables

$("a").click(function () {

   if ($this.has($("#a"))) { $this.attr("href", "#myfirsttable") }
   if ($this.has($("#a1"))) { $this.attr("href", "#mysecondtable") }

});

I haven't had time to try it out yet, and I'm a bit sleepy right now and not at my sharpest, but this is the simplest way I can think of at the moment.

Epiphany