使用DOM从具有特定ID的Div获取文本(getElementById帮助)

问题描述:

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.

我有以下代码片段我正在尝试从中获取文本: p>

 &lt; span class =“article-title1”&gt;&lt; div id =“user-sub-summary”&gt;喜欢获取文字&lt; / div&gt;&lt; / span&gt; 
&lt; div id  =“user-sub-intro”&gt;&lt; p&gt;这是我的介绍段落&lt; / p&gt;&lt; / div&gt; 
  code>  pre> 
 
 

我正在尝试 只需使用id“user-sub-summary”获取文本 Ulllyly我将获得此文本并将其显示在可编辑的文本框中,以便人们可以根据需要进行更改。 p> \ n

我的现有代码如下所示($ intro =上面的html代码段): p>

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

这只是在页面上返回'NULL' - 但我无法弄清楚为什么。 我试过在这里搜索,我用谷歌搜索,我到处寻找试图解决这个问题,但空手而归。 p> div>

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.