17

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?

Alessandro Vendruscolo
  • 12,889
  • 4
  • 29
  • 38

5 Answers5

5

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 !!

Riju Mahna
  • 5,850
  • 10
  • 49
  • 84
3

Since the <span> is not the immediate sibling of that <a>, we can't invoke .previousSibling or .previousElementSibling. Best solution might be to get the parent and query for the <span>

document.getElementById( 'div1' ).getElementsByTagName( 'a' )[ 0 ].addEventListener('click', function() {
    alert( this.parentNode.getElementsByTagName( 'span' )[ 0 ].textContent );
}, false);

Demo: http://jsfiddle.net/cEBnD/

jAndy
  • 212,463
  • 51
  • 293
  • 348
  • Pretty much the same as I answered, but not downvoted into oblivion for no apparent reason. Not to mention accessing the spans in a valid way, and no need to load a library. +1. Hrmpf, StackOverflow... – Cerbrus Jan 23 '13 at 11:31
  • If you use `addEventListener` and `textContent`, you can as well go for `querySelector` :P http://jsfiddle.net/Ralt/cEBnD/1/ – Florian Margaine Jan 23 '13 at 14:21
2

Update: Solutions with and without jQuery

This answer got so many downvotes for showing an example with jQuery that I decided to add more examples with vanilla JavaScript so that anyone could choose whether to use jQuery or not.

Generally, you can use .previousSibling in vanilla JavaScript, see:

and you can use .prev() in jQuery, see:

But keep in mind that those may not work in more complicated cases when you don't know the exact structure of your entire DOM.

Here are few examples of achieving that goal both using jQuery and with vanilla JavaScript, for simple cases with fixed DOM structure and for more complicated cases using classes.

Without classes

For the most simple DOM structures you might get away with putting event listeners on all links and relying on the implicit knowledge of the DOM, but this may not work for more complex situations - for those see the examples with classes below.

With jQuery:

$('a').click(function () {
  alert( $(this).prev().text() );
  return false;
});

See DEMO.

Without jQuery:

document.querySelectorAll('a').forEach(link => {
  link.addEventListener('click', () => {
    alert(link.previousSibling.previousSibling.innerText);
  });
});

Note that the previousSibling has to be used twice, because the empty text node that is between tha span and link would be used otherwise.

See DEMO.

Using classes

If the span is not immediately preceding your a element then you may also want to do it a little bit differently, also adding some classes to make sure that your code doesn't break any other links on the page:

With jQuery:

$('a.link').click(function () {
  alert( $(this).parent().find('span.text').text() );
  return false;
});

See DEMO.

Without jQuery:

document.querySelectorAll('a.link').forEach(link => {
  link.addEventListener('click', () => {
    alert(link.parentNode.querySelector('span.text').innerText);
  });
});

See DEMO.

The above code will bind click handlers to every a element with class "link" which will alert a text contained by its sibling span element with a class "text". (Of course the class names should be more descriptive than that.)

rsp
  • 91,898
  • 19
  • 176
  • 156
  • 8
    Don't bring a shotgun to a fencing match. OP didn't ask for jQuery, didn't tag the question with jQuery, and jQuery is just inefficient compared to normal JS. Yes, it's shorter code, but that's the only advantage. – Cerbrus Jan 23 '13 at 10:58
  • 1
    @Cerbrus jQuery **is** JavaScript and the question didn't mention any [prejudice](http://stackoverflow.com/questions/5099949/what-are-some-empirical-technical-reasons-not-to-use-jquery/5100169#5100169) against any particular technology. This is a solution that solves the problem described in the question (unlike yours). – rsp Jan 23 '13 at 11:04
  • 3
    jQuery is a library. It's a extra file to load, way more code to run, and doesn't help anyone to learn JS. Basics first, then libraries. Especially on simple matters such as this. I mean, loading a library for 3 lines of code? – Cerbrus Jan 23 '13 at 11:28
  • 2
    @Cerbrus If you post a solution that doesn't use jQuery **and works** for a general case without polluting the DOM with useless IDs that only add needless complexity to the markup generating templates **and** works across different browsers then we might have something to argue about. – rsp Jan 23 '13 at 11:40
1
<html>
<body>
    <div id="div1">
        <span>This is required</span>
        <a href="#" onclick="myclick(this.parentNode)">Click Me</a>
    </div>
</body>
<script>
    function myclick(x){
        var y = x.querySelector("span").innerHTML;
        alert(y)
    }
</script>
</html>

insted of span you can also give class name eg.,

<span class="classname">This is required</span>
x.querySelector(".classname").innerHTML
George Livingston
  • 2,120
  • 12
  • 11
0

Using jQuery:

$('#innerId').siblings()
Pang
  • 8,605
  • 144
  • 77
  • 113
  • 2
    The OP didn't ask for a jquery solution. Loading a massive external library to find the siblings is massive overkill. – Liam Apr 26 '17 at 12:53