2017-06-26 17 views
0

刪除第一部分url我在我的網頁中有url,我想從href中刪除前面部分(http://example.com/?),只保留第一個子div並從主div刪除其餘的div。我必須使用js或jQuery來做這件事我該怎麼做?從標籤

<div class="main"> 
    <a href="http://www.example.com/?https://someotherurl.org" target="_blank">google</a> 
    <div class="div-1"> 
    data 
    </div> 

    <div> 
    extra 
    </div> 
    <div> 
    extra 
    </div> 

</div> 

<!-- the final code I want is --> 



<div class="main"> 
    <a href="https://someotherurl.org" target="_blank">google</a> 
    <div class="div-1"> 
    data 
    </div> 


</div> 
+0

是你的'http://www.example.com/?'固定長度嗎? – Luca

+0

你到目前爲止嘗試過什麼? – styfle

+0

你的javascript看起來像什麼? – hRdCoder

回答

0

使用split,以獲得期望的結果,演示:https://jsfiddle.net/uxqsxo1v/1/

var url = $('a').attr('href'); 
url = url.split('?'); 
var newUrl = url[1]; 
$('a').attr('href',newUrl); 
+0

該href仍然是「http://www.example.com/?https://someotherurl.org」 –

+0

更新的代碼和提琴 – Rahul

+0

我的錯,我foagrgot添加''在'a'標籤 – Rahul

2

這裏是一個示例代碼:

var url=document.getElementsByClassName('main')[0].childNodes[1].href; 
 
url=url.split("?"); 
 
document.getElementsByClassName('main')[0].childNodes[1].href=url[1];
<div class="main"> 
 
    <a href="http://www.example.com/?https://someotherurl.org" target="_blank">google</a> 
 
<div class="div-1"> 
 
</div> 
 
</div>

我讓鏈看到我如何選擇元素和href屬性。

0

我喜歡querySelector因爲它比getElementsByClassName方法更相容,並且可容易地轉化到jQuery的

var anchor = document.querySelector('div.main>a'), 
 
     href = anchor.href.split("?")[1]; // assuming no other ? in the url 
 
anchor.href=href;
<div class="main"> 
 
    <a href="http://www.example.com/?https://someotherurl.org" 
 
    target="_blank">google</a> 
 
<div class="div-1"></div> 
 
</div>

的jQuery:

var $anchor=$("div.main>a"); 
 
$anchor.prop("href", $anchor.prop("href").split("?")[1]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="main"> 
 
    <a href="http://www.example.com/?https://someotherurl.org" target="_blank">google</a> 
 
    <div class="div-1"></div> 
 
</div>