0

I have a question about traversing a newly created element with jquery and greasemonkey.

I have this javascript snippet:

var content="some html string"
var el = $( '<div></div>' );
el.html(content);
GM_log(el.html());

The html string I added to the new div is something like:

Hello:<br> world<br> <img src="someimage.jpg" align="absmiddle" border="0">
<font color="#FF0000"> hello<br>
<img src="otherimage.gif" align="absmiddle" border="0"> 
test</font><br>    
----------

I am looking for a way to traverse the newly created div and access each tag/text separately .
for example, if I do:

GM_log(el.children());

I can only access the whole children instead of the single pieces of text/tag.
Can anyone suggest me how to do so?

nick2k3
  • 1,399
  • 8
  • 18
  • 25

2 Answers2

0

You can use find('*') to get all children and each() to traverse them.

el.find('*').each(function(){
    alert(this.tagName);
    alert($(this).html());
    alert($(this).text());
});
Adil
  • 146,340
  • 25
  • 209
  • 204
  • ok, one more question, your solution only displays the tag name, how do I access the text of that tag?or the html? – nick2k3 Nov 20 '13 at 10:36
  • $(this).html() or $(this).text() or this.innerHTML – Adil Nov 20 '13 at 10:38
  • mm it seems it does not work: $(this).html() shows empty strings except for the img tags. I might have find the culprit. If I do GM_log($(this)[0]) I get: [object XrayWrapper [object HTMLBRElement]] and XrayWrapper seems not to have an innerHTML implementation :( – nick2k3 Nov 20 '13 at 10:45
0

Use find() to fetch all descendant elements not just the direct children of the target element

GM_log(el.find('*'));
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531