开发者

jquery add element if not present

开发者 https://www.devze.com 2023-02-12 00:49 出处:网络
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.

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&g开发者_运维百科t;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?


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号