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

2
  • 3
    Javascript doesn't support multiline string. If you php variable is like you show use, it will never work. Commented May 2, 2014 at 20:14
  • @Karl-AndréGagnon, I just set it multiline to make it readable. In real, it is just one line. Commented May 2, 2014 at 20:23

2 Answers 2

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); 
Sign up to request clarification or add additional context in comments.

2 Comments

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...
@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.
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")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.