使用javascript从字符串html读取span标签值

时间:2018-10-05 07:27:48

标签: javascript jquery

我想获取来自HTML字符串的span值。示例代码链接-http://jsfiddle.net/9cCHy/58/

 var mystring = '<div class="table-cell"> <span>test</span>            </div> <span id="isbool" style="display:none">True</span></div>';

    var after = $('<div/>').html(mystring).find("span[id='isbool']").contents().unwrap().end().end().html();
    // want to capture value true without any dependency of html
    alert(after);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
   

3 个答案:

答案 0 :(得分:1)

.text()方法可以为您提供目标元素的文本内容:

var mystring = '<div class="table-cell"> <span>test</span>            </div> <span id="isbool" style="display:none">True</span></div>';

var after = $('<div/>').html(mystring).find("span[id='isbool']").text();
// want to capture value true without any dependency of html
console.log(after);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

答案 1 :(得分:0)

如果父标记上有一个类,则可以遍历其子代:

    var div0 = document.getElementsByClassName('table-cell')
    var children0 = div0[0].children;
    for (i = 0; i < children0.length; i++) {
     if (children[i].tagName = 'span') {
  var innerh = children[i].innerHTML; 
    alert('true:' + innerh);
    break
    } 
    } 

答案 2 :(得分:0)

您可以尝试以下代码

var mystring = '<div class="table-cell"> <span>test</span>            </div> <span id="isbool" style="display:none">True</span></div>';    
$ele = $.parseHTML(mystring); 
alert($ele[2]);