Подтвердить что ты не робот

Jquery удаляет все элементы, кроме первого

Использование jquery удаляет, как я могу удалить все теги span, кроме первого.

EDIT

 var html = var htm = $("#addin").find(".engagement_data:last-child").find(".keys_values").html();
    html='
       <span style="display:block;" class="k_v">
         <innput type="text" class="e_keys" style="width:65px;" placeholder="key"/>
         <input type="text" class="e_values" style="width:65px;" placeholder="value"/>
       </span>
       <span style="display:block;" class="k_v">
         <input type="text" class="e_keys" style="width:65px;" placeholder="key"/>
         <input type="text" class="e_values" style="width:65px;" placeholder="value"/>
       </span>
';
4b9b3361

Ответ 1

Попробуйте:

$(html).not(':first').remove();

или более конкретно:

$(html).not('span:first').remove();

Чтобы удалить его из DOM вместо переменной html, используйте свой селектор:

$('#addin .engagement_data:last-child .keys_values').not('span:first').remove();

Ответ 2

Или, в качестве альтернативы:

$('span').slice(1).remove();

срез()
Учитывая объект jQuery, который представляет собой набор элементов DOM,.slice() создает новый объект jQuery, содержащий подмножество элементы, заданные начальным и, необязательно, аргументом end.

старт
Тип: Integer
Целое число, указывающее положение, основанное на 0, при котором элементы начинают выбираться. Если значение отрицательное, это означает смещение от конца набора.

Источник: https://api.jquery.com/slice

Следовательно, $('span').slice(1).remove() будет выбирать и удалять все элементы после первого экземпляра.

Ответ 3

Используйте этот селектор:

$('span:not(first-child)')

Итак, ваш код:

$('span:not(first-child)').remove();

Ответ 4

Попробуйте это

$('html').not(':first').remove();

Ответ 5

Вышеупомянутое может работать для конкретного примера, когда в содержимом ничего нет, кроме дочерних элементов того типа, который вы ищете. Но у вас возникнут проблемы с более сложной разметкой:

<ul id="ul-id" class="f-dropdown tiny" data-dropdown-content="">
    <li>
    <div id="warningGradientOuterBarG" class="barberpole">
    <div id="warningGradientFrontBarG" class="warningGradientAnimationG">
        <div class="warningGradientBarLineG"></div>
    </div>
    </div>
    </li>
    <li>foo</li>
    <li>bar</li>
</ul>

var $ul = $('#ul-id')
$ul.not(':first')  //returns nothing
$ul.find(':first') // returns first <li>
$ul.find(':not(:first)') //returns the inner divs as well as the last two li's
$('#ul-id li:not(first-child)')  // this returns all li's
$('#ul-id li:not(:first)')  // this works: returns last two li's
$ul.find('li').slice(1) // this also works and returns the last two li's
$ul.find('li').slice(1).remove()   // and this will remove them

Ответ 6

Этот следующий код работает для меня:

$(html).children().not(':first').remove();