How can I get the ID of an element and pare it to a string OR another id ?
What I would like to do exactly is make a condition that would get the element's ID and pare it to a certain string or another element's ID.
I have this piece of code right now to pare my id to another id (which obviously doesn't work):
function Something(elemid)
{
if(elemid == document.getElementById('myid').id)
{
...
}
}
Or this piece of code to pare to a string (doesn't work either):
if(elemid == "mystring")
{
...
}
This is a simple problem, but still, I can't seem to find anything around here or even on other websites that would be what I am searching for. I can't use any JQuery whatsoever, so any Javascript only anwser would be really appreciated.
How can I get the ID of an element and pare it to a string OR another id ?
What I would like to do exactly is make a condition that would get the element's ID and pare it to a certain string or another element's ID.
I have this piece of code right now to pare my id to another id (which obviously doesn't work):
function Something(elemid)
{
if(elemid == document.getElementById('myid').id)
{
...
}
}
Or this piece of code to pare to a string (doesn't work either):
if(elemid == "mystring")
{
...
}
This is a simple problem, but still, I can't seem to find anything around here or even on other websites that would be what I am searching for. I can't use any JQuery whatsoever, so any Javascript only anwser would be really appreciated.
Share Improve this question edited Oct 4, 2020 at 12:11 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Jul 2, 2013 at 14:33 AquaSoleyAquaSoley 551 gold badge1 silver badge7 bronze badges 4-
3
document.getElementById('myid').id
is somewhat unnecessary because it will givemyid
always – bugwheels94 Commented Jul 2, 2013 at 14:35 - Why doesn' the second piece of code work? – Peter Commented Jul 2, 2013 at 14:44
-
What's the value of
elemid
? Are you sure it has the value it's supposed to have? – orique Commented Jul 2, 2013 at 14:50 - @orique: Yes, it has the value that it is supposed to have (verified troughout my function execution). – AquaSoley Commented Jul 2, 2013 at 14:59
2 Answers
Reset to default 8 if(elemid = document.getElementById('myid').id)
{
...
}
You need to pare it using ==
. A single =
is assign.
Also document.getElementById('myid').id
is pletely useless. You are specifying the id
directly and then attempt to return it.
As a simple test to show you how to pare an element.
<input type="text" id="hello" class="test" />
var element = document.getElementsByClassName("test")[0].id;
if (element === "hello") {
alert("Working");
}
http://jsfiddle/ckJP9/
How are you calling the function from jsp?
This code works for me:
function getValue(elementId)
{
//paring
if(document.getElementById("myHeader").id == elementId)
{
alert('It Works!');
}
}
and in the jsp
<h1 id="myHeader" onclick="getValue('myHeader')">Click me!</h1>