0

I have a snippet in Jquery like below

$(document).ready(function() {
    $('button#company').click(function() {
        var id = 0;
        var div = $(this).parents('div');
        var names = div.find('p[data-name*=name'+id+']');
        $.each(names, function(key,value) {
            console.log(value);
        } );
        console.log('ok');
    });
});

I have the following result in console, as expected

<p class="hidden" data-name="name0_0"> 
<p class="hidden" data-name="name0_1"> 
<p class="hidden" data-name="name0_2">
ok

The problem is, when I use console.log(value.val());. All script stops and anything happens, any error and even ok is not printed.

When I try to debug and put a breakpoint in console.log(value.val()) the script stops in the line, but anything happens.

I also tried .text() and .html() and I have the same problem.

console.log(names) results in:

 Object { 0: <p.hidden>, 1: <p.hidden>, 2: <p.hidden>, 3: <p.hidden>,
 4: <p.hidden>, length: 5, prevObject: Object, context:
 <button#company>, selector:
 "p[data-name*=name0]" }

The HTML is:

<div>
    <p class="hidden" data-name="name0_0">James</p>
    <p class="hidden" data-name="name0_1">John</p>
    <p class="hidden" data-name="name0_2">Carl</p>
    <button id="company" class="btn btn-default">Go!</button>
</div>
James
  • 1,653
  • 2
  • 31
  • 60
  • Try to wrap the value into jQuery call `$(value).val()`? Is there an error message when the js stops executing? – user3154108 Dec 06 '15 at 13:53
  • 1
    `value` isn't a jQuery object but DOM node, it hasn't `val()` method but `value` property. You should always open your console for debugging purpose and check error... Oh i just forgot, `p` element hasn't any value property defined, you surely want `$(value).text()` – A. Wolff Dec 06 '15 at 14:07
  • @A.Wolff I not consider this question a duplicate of "How can I debug my JavaScript code?", but your comment solves the problem. Thank You! – James Dec 06 '15 at 16:40

2 Answers2

1

The value in your case is the p html element (not jQueryfied), and as one, it has no .val(), .text() or .html() functions (these are all jQuery functions).

You can either use the DOM node property like this: value.innerHtml

or using jQuery like so: $(value).text()

Ronen Cypis
  • 21,182
  • 1
  • 20
  • 25
0

You need to use

 $.each(names, function(key,value) {
        console.log($(value).attr('data-name'));
    } );

Here is a fiddle https://jsfiddle.net/z8wngq2v/

val() is used for reading values from inputs. text() is used to read the text wrapped inside a target element html() is used to read the html content inside a target element.

You are trying to read an attribute inside a tag.

Also you need to jQuerify your selection so that you can use the jQuery function.

Bazinga777
  • 5,140
  • 13
  • 53
  • 92