2017-06-21 117 views
0

只想得到一个nestate span标签内的HTML ..获取嵌套span元素jQuery的Innerhtml?

<span class="select2-selection__rendered" id="select2-SearchByUser-container" title="chowdhury , nayan ([email protected])"> 
    <span class="select2-selection__clear">×</span> 
    mark john 
</span> 

我需要mark john和我尝试=>

alert($('#select2-SearchByUser-container').html()) 

我给输出/警报类似=>

<span class="select2-selection__clear">×</span>mark john 

有没有什么办法,我可以只有mark john ...帮助请...

回答

0

要做到你需要什么,你可以在元素检索最后textNode,像这样:

var text = $('#select2-SearchByUser-container').contents().filter(function() { 
 
    return this.nodeType == 3 && this.nodeValue.trim(); 
 
}).last().text().trim(); 
 

 
console.log(text);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<span class="select2-selection__rendered" id="select2-SearchByUser-container" title="chowdhury , nayan ([email protected])"> 
 
    <span class="select2-selection__clear">×</span> mark john 
 
</span>

0

试试这个:

https://jsfiddle.net/4nwp25Le/

jQuery(document).ready(function() { 
    var node = $('#select2-SearchByUser-container').contents().filter(function() { 
    return this.nodeType == 3; // text node 
    }); 
    alert(node.text()); 
}); 
+0

也试试我怎样才能改变$('#选择2 -SearchByUser-container')。text('hi john'); –

0

你的HTML到目前为止并不好,如果可能的话修复,这样你就可以得到不同的跨度米

如果你不拥有控制权HTML,可以给这样

$('#select2-SearchByUser-container').clone().children().remove().end().text() 

https://jsfiddle.net/qspoygox/

0

var el = document.getElementById("select2-SearchByUser-container"), 
 
    child = el.firstChild, 
 
    texts = []; 
 

 
while (child) { 
 
    if (child.nodeType == 3) { 
 
     texts.push(child.data); 
 
    } 
 
    child = child.nextSibling; 
 
} 
 

 
var text = texts.join(""); 
 
alert(text);
<span class="select2-selection__rendered" id="select2-SearchByUser-container" title="chowdhury , nayan ([email protected])"> 
 
    <span class="select2-selection__clear">×</span> 
 
    mark john 
 
</span>