2

How do I get the contents of a div using Jquery.

Here is my HTML:

<div class="DataRow" data-vendorid="67">
    <div class="DataColumn" style="width: 60%;">
        Barracuda
    </div>
    <div class="DataColumn" style="width: 20%; text-align: center;">
        1
    </div>
    <div class="DataColumn" style="width: 20%; text-align: center;">
        2
    </div>
</div>

Here is my Jquery:

$(function () {
    $('.DataRow').click(function () {
        // get value: Barracuda 
    });
});
Chris Levine
  • 273
  • 3
  • 10
  • There are 3 div's inside `.DataRow` div. Do you want to get the first div value? If you want Barracuda, you can use :first on children and get it .text() – Selvakumar Arumugam May 15 '12 at 15:27
  • 1
    Has all been answered already: [How to find an element within an element](http://stackoverflow.com/questions/7386100/how-to-find-an-element-within-an-element). The jQuery [selector](http://api.jquery.com/category/selectors/) and [traversal](http://api.jquery.com/category/traversing/tree-traversal/) contain information about all the methods you can use to find a certain element. Then have a look at [Select inner text (jQuery)](http://stackoverflow.com/questions/1644342/select-inner-text-jquery). – Felix Kling May 15 '12 at 15:37
  • I felt this was a duplicate at first too, but given that he doesn't have a unique class on the sub-div's, I think this a tricky question for a JQuery beginner, and not immediately apparent on how to solve / what keywords to zero in on. – Tom Halladay May 15 '12 at 15:45

5 Answers5

4
$(function () {
    $('.DataRow').click(function () {
        alert($(this).find(':first-child').text());
    });
});

Or:

$(function () {
    $('.DataRow').click(function () {
        alert($(this).children().first().text());
    });
});
Alex
  • 34,899
  • 5
  • 77
  • 90
3

If you need to get content of the clicked div it might help you.

$(function () {
    $('.DataRow').click(function (event) {

        alert(event.target.innerHTML);
    });
});​

DEMO 1

If you need to get only the first value:

$('.DataRow').click(function () {
    var first = $(this).children().eq(0).html();
    alert(first);
});​

DEMO 2

Eugene Trofimenko
  • 1,611
  • 1
  • 13
  • 19
1

If you need to get only "Baracuda", i.e. first div text, you could use innerHTML like this:

$(function () {
    $('.DataRow').click(function () {
        // get value: Barracuda 
        alert($(this).children("div")[0].innerHTML);
    });
});​

Here is an example.

Dovydas Navickas
  • 3,533
  • 1
  • 32
  • 48
0

You could also use this:

var value=$(".DataColumn").html();
karan k
  • 947
  • 2
  • 21
  • 45
0

To get the contents of the first child:

$('.DataRow').click(function () {
    var first = $(this).children(":first").html();
});

To get the contents of the third child:

$('.DataRow').click(function () {
    var third = $(this).children(":eq(2)").html();
});
VisioN
  • 143,310
  • 32
  • 282
  • 281