Reputation: 9080
I was able to set the focus of a table element by using the following code:
document.getElementById($('#' + ListBoxVal + ' tr:eq('+lstRow+')')
.attr('id')).focus();
I was able to verify that the id of the tr is in fact the correct id:
console.log($('#' + ListBoxVal + ' tr:eq('+lstRow+')').attr('id'));
What I need to do is get the actual HTML of that tr of the id I'm on..
Basically using some variation of this code, I need the html of the tr element:
console.log($('#' + ListBoxVal + ' tr:eq('+lstRow+')').attr('id'));
But I only need the beginning <tr>
html. I don't need the <td>
or the closing </tr>
.
<table>
<tr id='123'>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
<tr id='abc'>
<td>a</td>
<td>b</td>
<td>c</td>
</tr>
</table>
So I would only want the <tr id='123'>
for example.
Upvotes: 2
Views: 101
Reputation: 87763
var tr = $('#' + ListBoxVal + ' tr:eq('+lstRow+')')
var html = $('<tbody>').append(tr.clone()).html().replace(/>[\s\S]*/,'>')
console.log(html)
Details
You cannot directly get the HTML of an element, only the DOM innerHTML
. (same as jQuery html()
)
So first we make a new empty $('<tbody>')
. This does not exist in the document, it is therefore invisible and private to our JavaScript. Nothing else can see it.
We then add a copy of that tr with .append(tr.clone())
. (We have to copy it first or else we will remove it from the original location during append
)
Then we get the innerHTML
of the tbody with .html()
. We now have the "outer HTML" of the TR (<tr
...>
...</tr>
)
The final step is simple, we need to strip out everything after the first >
, so I use regex .replace(/>[\s\S]*/,'>')
(I like regex) (you can tell it is a regex because it is in slashes /
.../
)
The regular expression is >[\s\S]*
. It will start at the beginning and move forward until it finds a >
, then it will look for any whites
pace or non-whiteS
pace characters. ([\s\S]
), it will look for any number of these *
. Then it will replace >[\s\S]*
with >
.
Now you have the final product stored to the variable html
. :)
(FYI, when creating new HTML snippets with jQuery (like $('<tbody>')
), you can safely omit the end tag only if there are no children or attributes. See jQuery: Risk of not closing tags in constructors)
Upvotes: 2
Reputation: 7673
Using document.getElementById, and passing the ID to jQuery is a redundant operation - that's one of the first things jQuery is for! If you know the ID of the <tr>
element, you can just fetch it directly and use jQuery to get at the html:
$('#123').html()
Because ID's are (or should be) unique, you can safely use them to reference any element - you don't generally need to worry about starting from one of the containing elements.
I think I don't understand what you're trying to achieve properly - sorry!
Upvotes: 0