Javascript-форум (https://javascript.ru/forum/)
-   Общие вопросы Javascript (https://javascript.ru/forum/misc/)
-   -   Проверка вложенных li у ul (https://javascript.ru/forum/misc/69205-proverka-vlozhennykh-li-u-ul.html)

coolplayer37 05.06.2017 22:02

Проверка вложенных li у ul
 
Друзья, есть проблема проверки вложенных элементов li у ul. На странице есть куча ul списков с одинаковым id. Проблема в том, что сейчас JS наследует значения и для второго списка показывает тоже сообщение про пустоту. Помогите поправить.

html:
<ul id="products1">
</ul>	

<ul id="products1">
<li><li>
</ul>


js:
<script>
$(document).ready(function(){
if( ($("ul#products1").has("li").length == 0) ) {
  $("ul#products1").html("This <i>unordered list (products1)</i> is <span class='green'>empty</span>");
}
});
</script>

рони 05.06.2017 22:08

coolplayer37,
циклом по атрибуту id

рони 05.06.2017 22:18

coolplayer37,
или так
<!DOCTYPE html>

<html>
<head>
  <title>Untitled</title>
  <meta charset="utf-8">
  <style type="text/css">
  </style>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

  <script>
$(function() {
    $("ul[id='products1']").filter(":not(:has(li))").html("This <i>unordered list (products1)</i> is <span class='green'>empty</span>");
});
  </script>
</head>

<body>
<ul id="products1">
</ul>

<ul id="products1">
<li>test</li>
</ul>

<ul id="products1">
</ul>
</body>
</html>

рони 05.06.2017 22:24

Цитата:

Сообщение от рони
циклом по атрибуту id

<!DOCTYPE html>

<html>
<head>
  <title>Untitled</title>
  <meta charset="utf-8">
  <style type="text/css">
  </style>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

  <script>
$(function() {
    $("ul[id='products1']").each(function(indx, el){
       $(el).has("li").length || $(el).html("This <i>unordered list (products1)</i> is <span class='green'>empty</span>");
        });
});
  </script>
</head>

<body>
<ul id="products1">
</ul>

<ul id="products1">
<li>test</li>
</ul>

<ul id="products1">
</ul>
</body>
</html>


Часовой пояс GMT +3, время: 14:58.