2016-09-22 17 views
0

我有一個網頁在工作中重載我與形式的冗餘信息交互的結束:刪除網頁上的文本 - 下一個字符串「>」,直到跨度

Important text 
Other important text 
>> Not important 1 
>> Not important 2 
>> Not important 3 
Other important text 

我會喜歡一些JavaScript代碼我可以在Tampermonkey運行刪除所有在從>第一次出現開始,在給定範圍的結束標記結束所有跨文本

僞代碼示例:

var allSpanTags = document.getElementsByTagName('span');  

for(var thisSpanTag in allSpanTags){ 
    thisSpanTag.innerHTML.deleteStringBetween(index_of_first_">"_in_given_spans_inner_HTML , index_of_end_of_innerHTML_of_this_span_tag); 
} 

網絡野獸的錯綜複雜現在正以JavaScript(不是我的母語)在這個項目上讓我迷惑不解。我也不確定我是否以最有效的方式處理這個問題。

謝謝!

編輯:我讓我的代碼特別適用於具有某個className的跨度,以便它不會打破網頁上的其他內容。

var allSpans = document.getElementsByTagName("span"); 
for(var i = 0; i < allSpans.length; i++) { 
    try{ 
     if (allSpans[i].className.indexOf("textblock") > -1) { 
      allSpans[i].innerHTML = allSpans[i].innerHTML.replace(/&gt;.*/g, ''); 
     } 
    }catch(e){} 
} 
+1

可以避開'for'循環完全如果更換'document.getElementsByTagName ...'和'document.querySelectorAll( 'span.textblock')'。 – StardustGogeta

+0

謝謝!這是比我的className.indexOf哈哈更酷,更優雅的功能。你能解釋一下嗎?是不是我仍然需要一個for循環來循環遍歷document.querySelectorAll中的結果列表來執行每個元素的替換? – RenderedNonsense

+0

我的意思是說,編輯中的for循環不需要迭代頁面上所有的span,整體答案仍然可以遵循我的解決方案的格式。 – StardustGogeta

回答

2

Array.from(document.getElementsByTagName('span')).forEach(
 
    a => a.innerHTML = a.innerHTML.replace(/&gt;.*/g,'') 
 
);
<span>Please delete after the > sign here!</span><br> 
 
<span>Also, delete the sign > here!</span><br> 
 
<span>Don't > forget > me!</span>

這個怎麼解決呢?

編輯:現在用document.querySelectorAll[*=] CSS選擇器!

Array.from(document.querySelectorAll('span[class*=textblock]')).forEach(
 
    a => a.innerHTML = a.innerHTML.replace(/&gt;.*/g,'') 
 
);
<span class="atextblock">Please delete after the > sign here!</span><br> 
 
<span class="fun textblocks are not">Also, delete the sign > here!</span><br> 
 
<span class="whytextblock why">Don't > forget > me!</span><br> 
 
<span class="muahahahaha">> But not > here!</span>

+0

謝謝!很棒! – RenderedNonsense

+0

@Render我很樂意幫忙! :) – StardustGogeta

+2

只需指出函數簽名'function(a,b,c)'是沒有必要的。你可以引用'a'並運行'a.innerHTML = ...',那就行了。不需要引用索引或數組引用本身。 – wpcarro

相關問題