选择父div中的特定元素 [英] select specific elements in parent div

查看:55
本文介绍了选择父div中的特定元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从div获取一篇文章,问题是当我使用 $('#article')时它会获得所有内容.html()是否有只需在没有其他元素的父div中获取特定html的方法?

im trying to get an article from a div, and the problem is it gets everything when i use $('#article').html() is there a way for just getting a spesific html inside the parent div without other elements?

<div id="article">
This is an article
blabla
<br/>
<b>something bold here</b>
    <div id="unknown">{some javscript}</div>
    <link type="anything" url="somewhere">
    <style>
        .something
    </style>
the end of the article
</div>

应该返回

this is an article
blabla
<br/>
<b>something bold here</b>
the end of the article


推荐答案

参见< a href =http://jsfiddle.net/TULKC/ =nofollow> http://jsfiddle.net/TULKC/

var el=document.getElementById('article'),
    text=getText(el);
function getText(el){
    var els=el.childNodes,
        t='';
    for(var i=0;i<els.length;i++){
        if(els[i].nodeType==3){//If it's a text node
            if(!/^\s+$/.test(els[i].nodeValue)){//We avoid spaces
                t+=els[i].nodeValue;
            }
        }else if(els[i].nodeType==1){//If it's an element node
            var nName=els[i].nodeName.toLowerCase(),
                c=check(nName);
            if(c==1){//Allowed elements
                t+='<'+nName+'>'+getText(els[i])+'</'+nName+'>';
            }else if(c==2){//Allowed self-closing elements
                t+='<'+nName+' />';
            }
        }
    }
    return t;
}
function check(nodeName){
    switch(nodeName){
        case 'b': return 1;//Allowed elements
        case 'br':return 2;//Allowed self-closing elements
        default:return 0;
    }
}
alert(text);

注意:您可以通过这种方式添加更多例外:

Note: You can add more exceptions this way:

switch(nodeName){
    case 'b': case 'a':  return 1;//Allowed elements
    case 'br':case 'img':return 2;//Allowed self-closing elements
    default:return 0;
}

(好吧,如果你使用HTML5, img 不是自动结算元素)

(Well, if you use HTML5, img is not a self-closing element)

编辑:

如果你想保留属性,你可以使用以下功能

If you want to keep the attributes, you can use the following function

function getAttr(el){
    var attr=el.attributes,
        t='';
    for(var i=0;i<attr.length;i++){
        t+=' '+attr[i].nodeName+'="'+attr[i].nodeValue+'"';
    }
    return t;
}

然后

if(c==1){
    t+='<'+nName+getAttr(els[i])+'>'+getText(els[i])+'</'+nName+'>';
}else if(c==2){
    t+='<'+nName+getAttr(els[i])+' />';
}

在此处查看: http://jsfiddle.net/TULKC/4/

这篇关于选择父div中的特定元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆