I am trying to append a string, myoutput, right after a specific row in a table similar to this one:
<table>
<tr data-my_id='1'> <td> content </td> </tr>
<tr data-my_id='2' data-my_other_id='1' > <td> content </td> </tr>
<tr data-my_id='3' data-my_other_id='2' > <td> content </td> </tr>
</table>
So let's say I want to append my output string after the tr with data-my_other_id='2'
(note that in my code, my_other_id = 2
already )
I am trying to accomplish it doing this:
var want = $("tr").find("[data-my_other_id='" + my_other_id + "']").index();
after finding the index, I want to append my output strhing to this row...
$(want).insertAfter(...?);
Also... I noticed whenever I do
alert( want = $("tr").find("[data-my_other_id='" + my_other_id + "']").length)
I get 0 ...
Help please and let me know if my question is not clear enough so I can explain better.
Answer: Use the CSS Attribute Selector You can use the CSS attribute selectors to find an HTML element based on its data-attribute value using jQuery. The attribute selectors provide a very powerful way to select elements.
The jQuery. hasData() method provides a way to determine if an element currently has any values that were set using jQuery. data() . If there is no data object associated with an element, the method returns false ; otherwise it returns true .
Which is the correct jQuery selector to select current HTML element? Explanation: The $(this) selector is used to select current HTML elements.
I'm assuming you want to update the content rather than append, but it doesn't really change anything. I don't think you want to use find() that way. Try something like:
var $row = $('tr[data-my_other_id="' + id + '"]');
// should be the index of the tr in the <table>
// this may not be a good idea though - what if you add a header row later?
var index = row.index() + 1; // if you want 1-based indices
$row.find("td").text("I am row #" + index);
This is because find will no search siblings, only children. Try attaching your search to table.
html:
<table>
<tr data-my_id='1'> <td> content </td> </tr>
<tr data-my_id='2' data-my_other_id='1' > <td> content </td> </tr>
<tr data-my_id='3' data-my_other_id='2' > <td> content </td> </tr>
</table>
js:
var my_other_id = 2;
alert( $("table").find("[data-my_other_id='" + my_other_id + "']").length);
demo: http://jsfiddle.net/gDb3A/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With