0

I have this javascript (jquery), in which I've defined a variable. This variable contains a string which might have one or more ul's in it. I want the script to select every ul and run a function for each of them.

But unfortunately, nothing happens when loading the page.

<script type="text/javascript">
    var wid_tekst1 = "<?php echo $wid_tekst1; ?>";
    $(wid_tekst1).find('ul').each(function() {
        alert('hoi');
    })
</script>

The $wid_tekst1 contains:

<p>test tekst 1</p>
<ul>
    <li>testitem</li>
    <li>testitem</li>
    <li>testitem</li>
    <li>testitem</li>
    <li>testitem</li>
    <li>testitem</li>
    <li>testitem</li>
</ul>
<p>test</p>

Thank you

David
  • 2,987
  • 1
  • 29
  • 35
Bram
  • 273
  • 1
  • 10

2 Answers2

1

Since the uls are top level elements in your collection you should use filter instead of the find method. If you want to use the find method you can set the string as innerHTML of another element:

$('<div/>').html(wid_tekst1).find('ul').each(func); 
Ram
  • 143,282
  • 16
  • 168
  • 197
  • Thanks that worked! Didn't know about the filter-method. So to be clear, the find-method will only work on variables defined as html and the filter-method works on all variables? I'll accept your answer in a couple of minutes... – Bram May 02 '14 at 20:20
  • @user3235648 You are welcome, actually the difference is the level of elements in a jQuery collection. `find` selects _the matching descendant elements_ of the collection's elements and `filter` filters _the elements in the collection_. – Ram May 02 '14 at 20:25
0

You could query the dom directly, if the UL objects exist there.

$("ul")

Or you could place your html string into a JQuery object like this example https://stackoverflow.com/a/11047751/3066711

$('<div/>').html(wid_tekst1).find("ul")
Community
  • 1
  • 1
Shriike
  • 1,351
  • 9
  • 20