Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
176
rated 0 times [  179] [ 3]  / answers: 1 / hits: 33423  / 11 Years ago, tue, july 2, 2013, 12:00:00

How can I get the ID of an element and compare 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 compare it to a certain string or another element's ID.



I have this piece of code right now to compare 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 compare 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.


More From » dom-events

 Answers
82
 if(elemid = document.getElementById('myid').id)
{
...
}


You need to compare it using ==. A single = is assign.



Also document.getElementById('myid').id is completely useless. You are specifying the id directly and then attempt to return it.



As a simple test to show you how to compare an element.



<input type=text id=hello class=test />

var element = document.getElementsByClassName(test)[0].id;

if (element === hello) {
alert(Working);
}


http://jsfiddle.net/ckJP9/


[#77256] Monday, July 1, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jameson

Total Points: 534
Total Questions: 103
Total Answers: 102

Location: Lithuania
Member since Fri, Sep 4, 2020
4 Years ago
jameson questions
;