Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery add element if not present

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?

like image 943
KdgDev Avatar asked Feb 20 '11 20:02

KdgDev


2 Answers

You 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.

like image 121
user113716 Avatar answered Oct 05 '22 23:10

user113716


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.

like image 21
Dogbert Avatar answered Oct 06 '22 00:10

Dogbert