Hanny
Hanny

Reputation: 2159

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

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.

Upvotes: 1

Views: 1534

Answers (3)

JCollins
JCollins

Reputation: 71

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.

Upvotes: 0

Cygnusx1
Cygnusx1

Reputation: 5409

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

Upvotes: 0

Brandon Bissoon
Brandon Bissoon

Reputation: 131

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;

Upvotes: 1

Related Questions