Varun Sridharan
Varun Sridharan

Reputation: 1978

Jquery to get the contents of a div

How can I get the contents of a <div> when a link is clicked

eg :

there are two div tags

<div id="1" > This Is First Div </div>
<div id="2" > This Is Second Div </div>
<a href="#" id="click" >Click Here</a>

When the link is clicked, I need to get the content as:

This Is Fist Div
This Is Second Div

Upvotes: 0

Views: 128

Answers (2)

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123377

If I well understood

$('a').on('click', function(ev) {
   ev.preventDefault();
   $($(this).prevAll('div').get().reverse()).each(function() {
     alert ($(this).text())
   })
});

As a sidenote, the id attributes you choose are not valid (they cannot start with a digit)

Example fiddle : http://jsfiddle.net/533qX/

edit. With one single alert

$('a').on('click', function(ev) {
   var text = "";
   ev.preventDefault();
   $($(this).prevAll('div').get().reverse()).each(function() {
     text += $(this).text() + "\n";
   })
   alert(text);
});

Upvotes: 2

Glo
Glo

Reputation: 604

function alertDiv(divId){
    $('#click').on('click', function(e){
       alert ($(divId).text());
       e.preventDefault();
    });
}

alertDiv('#one');
alertDiv('#two');

http://jsbin.com/ebowim/2/edit

Upvotes: 3

Related Questions