3

I want to reload a particular div, which has an id corresponding to a table element's id... (the div has only one table child).

the alert says tID is undefined.

javascript:

function (msg) {
         var tID = $("table", msg).attr('id');
         alert(tID);
         $("#reloadme_"+tID).html(msg);
}

html:

 <div id="reloadme_2036">

        <table id="2036"  class="customCSSclass">
            ...table contents...
        </table>

   </div>

Where have I gone wrong?

8
  • 1
    What exactly are you supplying for msg? Commented Jan 16, 2013 at 2:36
  • 1
    what is the value of msg variable? Why you pass this to the selector $("table", msg) ? Commented Jan 16, 2013 at 2:37
  • random shot: try var tID = $(msg).find('table').attr('id'); in case msg is a HTML string. Commented Jan 16, 2013 at 2:38
  • A HTML string, something like: <table id="2036" class="customCSSclass"> ...table contents... </table> Commented Jan 16, 2013 at 2:39
  • Fabricio, thanks for the try. It also says undefined for that line. Commented Jan 16, 2013 at 2:42

3 Answers 3

3

find looks for descendants of the current set of elements inside the jQuery object, you should use .filter which filters the elements in the jQuery object itself:

$('<table id="001">[...]</table>')
//the jQuery object will contain a reference to the parsed <table> element,
//so you have to .filter() the jQuery object itself to extract it

Of course, if it is the only element inside the jQuery object, there is no need for filtering. =]

Also, you'd use .find for e.g. looking for tr/tds (or any other element(s)) that are descendant of the table element referenced inside of your jQuery object.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks mate, but it appears I can't vote this up because I am so disreputable :P
@ninjamario no problem, you can still tick it as the accepted answer clicking in the "V" below the up/down buttons. =]
1

Maybe this is what you're looking for?

function reload(msg) {
  var tID = msg.match(/id="(\d{1,4})"/i)[1]; //find 1 to 4 digits in the id attribute
  alert(tID);  //alerts 2036
  $("#reloadme_"+tID).html(msg); //adds the content to the div
}
reload('<table id="2036" class="customCSSclass"> ...table contents... </table>');

If so, what you are likely looking for is javascript's .match() method which will find the id number within a string.

Check out the JSFiddle.

1 Comment

Thanks for an alternative solution :) match() seems like a useful function.
0

You have to try like this

var msg='<table id="2036"  class="customCSSclass"></table>';
alert($(msg).attr("id"));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.