2017-07-06 38 views
0

如果我的問題是不明確的,我不希望它返回一個node.I內的所有內容outerhtml不想those.For例如:是否有可能使用jquery或普通javascript在標籤的封閉'<' and '>'中獲取字符串?

<div id="foo" class="something" style="width:80%; display:inline-block"> 
 
    Hello! 
 
    <div id="bar" class="something_else"> 
 
    How are you?Hope you are doing well! 
 
    </div> 
 
</div>

現在,「富」的outerHTML將給予DOM structure.I的整個字符串表示只想

div id="foo" class="something" style="width:80%; display:inline-block" 

是否有可能得到這個沒有使用正則表達式/字符串匹配?

+0

我建議你先糾正你預期的結果。目前的一個沒有意義。 – tilz0R

+0

對不起 – 4words

+6

所以你想'div'的開始標籤,沒有'<' and '>'分隔符...?這是一個非常奇怪的要求,看起來像是X/Y問題。你爲什麼需要這個? –

回答

4

使用JavaScript element.nodeName和element.attributes形成的字符串:

var foo = document.getElementById('foo'); 
 
console.log(crazyString(foo)); 
 

 
function crazyString(el) { 
 
    var a = [el.nodeName]; 
 
    var atts = el.attributes; 
 
    for (var i=0; i < atts.length; i++) { 
 
    a.push(atts[i].name + '="' + atts[i].value + '"'); 
 
    } 
 
    return a.join(" "); 
 
}
<div id="foo" class="something" style="width:80%; display:inline-block"> 
 
    Hello! 
 
    <div id="bar" class="something_else"> 
 
    How are you?Hope you are doing well! 
 
    </div> 
 
</div>

+0

這就是解決方案。我不明白Johann Karlsson會得到5個upvotes ...我爲你的解決方案投票。 –

+1

@FrankWisniewski,因爲易碎的單線很容易消化。 – canon

+0

是的,所以它似乎... –

4

你可以得到outerHTML,然後分析你想要的部分:

console.log(
 
    document.getElementById('foo').outerHTML.match(/<([^>]+)>/)[1] 
 
);
<div id="foo" class="something" style="width:80%; display:inline-block"> 
 
    Hello! 
 
    <div id="bar" class="something_else"> 
 
    How are you?Hope you are doing well! 
 
    </div> 
 
</div>

+2

同意,但OP不希望正則表達式匹配 –

+4

''div id =「foo」title =''...'你根本無法使用正則表達式解析html。在簡單的,已知的情況下可能會好起來的。 –

+1

OP:*「是否可以在不使用正則表達式** /字符串匹配的情況下得到此** *」 –

1

你可以嘗試這樣的事情,

var element = document.getElementById("foo"); 
 

 
var tag = element.tagName; \t 
 
    $.each(element.attributes, function() { 
 
    tag += " "+ this.name + '"'+ this.value+ '"'; 
 
    }); 
 
    alert(tag);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="foo" class="something" style="width:80%; display:inline-block"> 
 
    Hello! 
 
    <div id="bar" class="something_else"> 
 
    How are you?Hope you are doing well! 
 
    </div> 
 
</div>

+2

'$(「#foo 「).each('..開始挺不好.. – Kaddath

+0

更正..謝謝。 – Arun

0

另一個版本使用Array#reduce

let el = document.getElementById('foo'); 
 

 
let res = [].slice.call(el.attributes).reduce((a, c) => { 
 
    return a.concat(c.name + '="' + c.value + '"'); 
 
}, [el.tagName.toLowerCase()]).join(' '); 
 

 
console.log(res)
<div id="foo" class="something" style="width:80%; display:inline-block"></div>

相關問題