Поиск по этому блогу

четверг, 5 ноября 2015 г.

Используем jQuery для чистки фрагментов html кода

Понадобилось скопипастить с чужого сайта часть статьи. Если текст большой, то выгоднее тырить фрагменты вместе с html разметкой. Можно ли почистить/изменить разметку перед вставкой на свой сайт? Здесь я проделал это через консоль с помощью команд вроде $("p[style*='bold']").contents().unwrap().wrap('

'); или $( "p" ).removeClass( "myClass noClass" ).addClass( "yourClass" );
На сайте jQuery есть не только хороший справочник, но и форум. All of the methods in this section manipulate the DOM in some manner.
A few of them simply change one of the attributes of an element (also listed in the Attributes category), while others set an element's style properties (also listed in the CSS category).

jQuery Category: Manipulation All of the methods in this section manipulate the DOM in some manner. A few of them simply change one of the attributes of an element (also listed in the Attributes category), while others set an element's style properties (also listed in the CSS category). Still others modify entire elements (or groups of elements) themselves—inserting, copying, removing, and so on. All of these methods are referred to as "setters," as they change the values of properties. A few of these methods—such as .attr(), .html(), and .val()—also act as "getters," retrieving information from DOM elements for later use.
forum.jquery.com remove the tags without the content between them
Remove attr isn't work
Clearing Inline CSS Properties With jQuery - "неправильная подсказка"

Неправильная подсказка

In [ ]:
$('p').attr( "style", "" );

Правильная со страниц форума

In [ ]:
$('p').removeAttr('style');
In [ ]:
$('strong').contents().unwrap()
$('span').contents().unwrap()
In [ ]:
 $("div span font").contents().unwrap().unwrap();
In [ ]:
$('div font').each(function() {
    $(this).replaceWith($(this).text());
});

Убрать или заменить атрибут класа

Сначала я попробовал

In [ ]:
$('p').removeAttr('style'); # не работает

Но ничего не получилось, оказалось, что для класса есть специальный атрибут.

In [ ]:
$( "p" ).removeClass( "myClass noClass" ).addClass( "yourClass" );

Для дальнейшего чтения и экспериментов

.attr()

Get the value of an attribute for the first element in the set of matched elements or set one or more attributes for every matched element.

.prop()

Get the value of a property for the first element in the set of matched elements or set one or more properties for every matched element.

.removeAttr()

Remove an attribute from each element in the set of matched elements.

.removeProp()

Remove a property for the set of matched elements.

.val()

Get the current value of the first element in the set of matched elements or set the value of every matched element.

Значение атрибута class первого тега div в наборе

In [ ]:
$('div').attr('class'); 

В теге P с атрибутами STYLE, а в значениях втрибуте есть BOLD

In [ ]:
<p style="font-size: 16px; color: #000000; font-weight: bold; 
          font-family: PT Sans; background: #f0f6f8; 
          padding: 15px 0 15px 30px; margin: 0;">

Объекты жилищно-гражданского назначения

</p>
In [ ]:
$("p[style*='bold']"); 

Уберем в теге инлайн стили и вставим атрибут класса

In [ ]:
$("p[style*='bold']").contents().unwrap().wrap('<p class="he4"></p>'); 


Посты чуть ниже также могут вас заинтересовать

Комментариев нет: