javascript - Getting nodes/child nodes from html
Get the solution ↓↓↓The first thing I do is I echo some html code:
echo "<div>
<file>somefile</file>
<file>another file</file>
</div>";
Then I through JavaScript find all instances of file:
var file = document.getElementsByTagName("file");
Then I am able to get values from each file by:
file[index].childNodes[0].nodeValue
Now I want to add another level to the<file>
like this:
echo "<div>
<file>
<em1>element1</em1>
<em2>element2</em2>
</file>
</div>";
How can I get those em values? I want to do something like:
file[index].getValueFromEm1...
Answer
Solution:
you can still access the content of the ems like you did with the original content.
var files= document.getElementsByTagName("file");
files[0].childNodes[0].textContent
files[0].childNodes[1].textContent
Answer
Solution:
Try
file[index].childNodes[0].nodeValue
file[index].childNodes[1].nodeValue
etc...
Answer
Solution:
try this
PHP
<?php
echo "<div>
<file>
<em1>element1</em1>
<em2>element2</em2>
</file>
<file>
<em1>element3</em1>
<em2>element4</em2>
</file>
</div>";
?>
JS
<script>
var file = document.getElementsByTagName("file");
for(var i=0; i<file.length; i++)
{
var filenodes = file[i].childNodes;
for(var j=0; j<filenodes.length; j++)
{
var element_text = filenodes[j].innerHTML;
if(typeof element_text!= 'undefined')
{
alert(element_text);
}
}
}
</script>
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: using $this when not in object context
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.