Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get value from r.fn.init (JQuery selector context)

Hi I try to receive a value from span from table like this:

function getValueFromSibling(this) {
    var id = $(this).parent().siblings('span.childSibbling');
}

Table looks like this:

<tr>
    <td>
      <button type="button" onClick="getValueFromSibling()"></button>
    </td>
    <td>
      <span class="childSibbling">100</span>
    </td>
</tr>

But I receive something like this:

id = r.fn.init [prevObject: r.fn.init(1)]

I found that is simple form of:

var jQuery = function( selector, context ){
   return new jQuery.fn.init( selector, context );
};

So there is the question. How to receive InnerHTML from <span>, or how to convert r.fn.init [prevObject: r.fn.init(1)] to value?

var result = id.val(); and var result = id.get(); dosen't work

like image 568
Adriano Avatar asked Jan 05 '18 08:01

Adriano


People also ask

What is S FN init in jQuery?

fn. init( selector, context ); }; So when you use a selector you are creating an instance of the jquery function; when found an element based on the selector criteria it returns the matched elements; when the criteria does not match anything it returns the prototype object of the function.

What is jQuery FN?

fn is an alias for jQuery. prototype which allows you to extend jQuery with your own functions. For Example: $.fn. something = function{}

What is a jQuery element?

version added: 1.0jQuery( "element" ) Refers to the tagName of DOM nodes.


1 Answers

First of all, this inside your function getValueFromSibling is in window scope pass this context when calling the function

 onClick="getValueFromSibling(this)"

And there are few things missing like text() to get the text you want. Try one below

Better way (actually recommended way):

Html

<tr>
    <td>
      <button type="button" class="some-button"></button>
    </td>
    <td>
      <span class="sibbling">100</span>
    </td>
</tr>

Jquery

$(function(){
  $('.some-button').click(function(){
      var id = $(this).closest('tr').find('.sibbling').text();
          // .closest() gets the closest tr parent .
          // .find() finds the element with class 'sibbling' inside that `tr`
          // .text() gets the text inside the element.
  });
});
like image 98
bipen Avatar answered Oct 26 '22 12:10

bipen