开发者

Simple HTML DOM how to access the elements at the top level only

i'm stuck with the subj question. this is the sample code:

include('./simple_html_dom.php');
$html = str_get_html("
<cols>
    <br>
    <col>
        content1
        <br>
        content1
    </col>
    <br>
    <col>
        <br>
        content2
        <br>
        content2
    </col>
    <br>
</cols>");

foreach($html->find('cols br') as $br) { echo $br->outertext; }

this gives me all the <br> tags inside the <cols> tag, but i need the <br>'s only on the top level.

$html->find('cols > br') doesnt work also(

UPDATE resolve this :

foreach($html->find('cols') as $cols_tag_content)开发者_运维知识库 {
    for($node = 0; $node < count($cols_tag_content->children()); $node++) {
        if($cols_tag_content->children($node)->tag == "br") {
            //doing whatever you want with br. i just remove it
            $cols_tag_content->children($node)->outertext = "";
        }
    }
}
this works with <br> and <br />


foreach($html->find('cols') as $cols_tag_content) {
    for($node = 0; $node < count($cols_tag_content->children()); $node++) {
        if($cols_tag_content->children($node)->tag == "br") {
            //doing whatever you want with br. i just remove it
            $cols_tag_content->children($node)->outertext = "";
        }
    }
}


Have you tried 'cols>br'? I think the 'cols > br' may be throwing it off.

See http://www.w3schools.com/css/sel_element_gt.asp also for maybe more information.

I think jQuery allows for the spacing though.

UPDATE

I restructured your pseudo-html above to use divs with classes to the following:

<div class="cols">
    <br />
    <div class="col">
        content1
        <br />
        content1
    </div>
    <br />
    <div class="col">
        <br />
        content2
        <br />
        content2
    </div>
    <br />
</div>

Executing the following jQuery script works now:

var brs= $('div.cols > br');
alert("Found "+brs.length+" brs");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜