开发者

Get Text from a Div with specific ID's using DOM (getElementById help)

开发者 https://www.devze.com 2023-03-20 11:12 出处:网络
I have the following code snippet I\'m trying to get the text from: <span class=\"article-title1\"><div id=\"user-sub-summary\">Love to get text</div></span>

I have the following code snippet I'm trying to get the text from:

<span class="article-title1"><div id="user-sub-summary">Love to get text</div></span>
<div id="user-sub-intro"><p>this is my intro paragraph</p></div>

I'm trying to get just the text in the with the id "user-sub-summary" Ultimately I'm going to get this text and display it in an editable textbox so people can change this if they would like.

my existing code looks like this ($intro = the html snippet above开发者_运维知识库):

$dom = new DOMDocument;
$dom->loadHTML($intro);
var_dump($dom->getElementById('user-sub-summary'));

This just returns 'NULL' on the page - but I can't figure out why. I've tried searching here, I've googled, I've looked everywhere to try and figure this out but have come up empty handed.


You need to declare a doctype. http://www.php.net/manual/en/domdocument.getelementbyid.php#100402

And it's always a good practice to validate your data before parsing.

$dom->validateOnParse = true;


first : I suggest using a javascript framework (JQuery)

second : be sure that your DOM is finished loading.

$(document).ready(function(){
    alert($("#user-sub-summary").html());
});

Hope it help


If you are using dynamic HTML or jQuery, make sure the dynamic object is appended to the document model before trying to 'get' or select it. That is, Javascript's getElementById method searches DOM objects attached to the document root (directly or through other objects attached to one another).

In Javascript, see here for an example appending dynamic content. Insert alert(currentDiv.innerHTML); after line 11 to see the desired text.

In jQuery, use (where "parentId" is the Id of an object attached to the DOM document root):

var childObject = $('<div id="childId">Text</div>');
$("#parentId").append(childObject);
alert( $("#childId").text() );

or

alert( childObject.text() );

And for the comment by user744186, I assume this is running on the client.

0

精彩评论

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