I'm reading a book on jQuery and it has some simple tasks and examples.
I'm trying out the adding of an element to a table, but only if the item is not yet present.
The table is this:
<table border="1" cellspacing="0">
<tr>
<td>Spaghetti</td>
<td>Karl</td>
</tr>
<tr>
<td>Pasta</td>
<td>David</td>
</tr>
</table>
The problem is: we're not allowed to add any classes or id's.
The idea is to add a caption. And of course, if the button is pressed 2 times, no second caption is added.
I tried this:
if(!jQuery.contains('table','caption')) {
$('table').append('<caption>Orders</caption>');
}
And this
if(!($("table:contains('caption')"))) {
$('table').append('<caption>Orders</caption>');
}
But neither work. I've read the jQuery api on the functions and selectors, I thought these would work but they don't. What do I need to do?
I'm reading a book on jQuery and it has some simple tasks and examples.
I'm trying out the adding of an element to a table, but only if the item is not yet present.
The table is this:
<table border="1" cellspacing="0">
<tr>
<td>Spaghetti</td>
<td>Karl</td>
</tr>
<tr>
<td>Pasta</td>
<td>David</td>
</tr>
</table>
The problem is: we're not allowed to add any classes or id's.
The idea is to add a caption. And of course, if the button is pressed 2 times, no second caption is added.
I tried this:
if(!jQuery.contains('table','caption')) {
$('table').append('<caption>Orders</caption>');
}
And this
if(!($("table:contains('caption')"))) {
$('table').append('<caption>Orders</caption>');
}
But neither work. I've read the jQuery api on the functions and selectors, I thought these would work but they don't. What do I need to do?
Share Improve this question asked Feb 20, 2011 at 20:24 KdgDevKdgDev 14.5k48 gold badges124 silver badges159 bronze badges2 Answers
Reset to default 19You can get it done without the if()
statement if you'd like:
$('table:not(:has(caption))').prepend('<caption>Orders</caption>');
This uses the not-selector
(docs) and the has-selector
(docs) to select <table>
elements that do not have a nested <caption>
element.
It also uses the prepend()
(docs) method to give a more expected placement in the DOM. It won't affect the actual display on the page.
This should work
if($("table caption").length === 0) {
// append caption
}
The jQuery call returns all the caption elements present inside all table elements. .length
returns the count of the elements. If it's 0, append the caption.