get nearby sibling in javascript

user2003007 picture user2003007 · Jan 23, 2013 · Viewed 20.9k times · Source

I have a certain DIV structure with an anchor tag in between somewhere. On click of the link, I need to fetch the value of another span element within the parent div and do something, (say, alert it).

The html is like this :

...
<div id="div1">
  ...
  <span>This is reqd</span>
  ...
  <a href="#">Click Me </a>
  ...
</div>
...

The entire div is repeated many times in the page. When I click on the a I want to alert "This is reqd".

Can the HTML be searched like this?

Answer

Riju Mahna picture Riju Mahna · Jan 23, 2013

For a single span element, it should be pretty easy,. Just call a myFunction(this) on click of the link and manipulate the DOM like this :

function myFunction(currObj){
var parentofSelected = currObj.parentNode; // gives the parent DIV

var children = parentofSelected.childNodes;
for (var i=0; i < children.length; i++) {
    if (children[i].tagName = "span") {
        myValue= children[i].value;
        break;
    }
}
alert(myValue); // just to test

 } // end function

Hope this works. It did for me !!