最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jquery add element if not present - Stack Overflow

programmeradmin2浏览0评论

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 badges
Add a comment  | 

2 Answers 2

Reset to default 19

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)

  1. 暂无评论