2

I have a basic string variable which stores HTML content.

The html in the string is a complex list like the following:

<ul>
<li>One
  <ul>
    <li>a</li>
    <li>b</li>
    <li>c</li>
  </ul>
</li>
<li>Two
  <ul>
    <li>d</li>
    <li>e</li>
    <li>f
      <ul>
        <li>g</li>
        <li>h</li>
        <li>i</li>
      </ul>
    </li>
  </ul>
</li>
<li>Three</li>

The above is a simplified example, but as you can see, the are an unknown number of list elements. A list element can contain another list. There is an unknown number of levels (a list element can have unknown (probably max 9) parent <ul>'s.

Now when I turn this string into HTML I do the following:

var obj = $(myHTMLString);

However, this only returns the first level of list elements - So in the following for loop, only the first level is searched. I know how to search children elements (in the else section on the code), but I would require to do this for all levels of the list - which is unknown.

for (var i=0; i<obj.length;i++) {
    if ( obj[i].id == someOtherVariable ) {
        //we have found it
    }
}

Is there a way to search my html variable (obj) for all list elements?

I would like to add that when I console.log( $(myHTMLString) ); It looks like this:

screenshot

4 Answers 4

3

Yes:

var lis = $(myHTMLString).find("li");

to iterate through them:

lis.each(function(index, li){
   //do your thing. i is the index in the array, li is the li element
})
Sign up to request clarification or add additional context in comments.

Comments

1

You can use a selector as you normally would, just using the HTML string as a context. Try this:

$('li', $(myHTMLString)).each(function() {
    // do something with the li
});

Comments

0

You can find all li in your list :

var liElements= $(myHTMLString).find('li');

Comments

0

well as it is not only li elements i guess i would walk down the child nodes

function searchli(object){
for each element in $(this).children()
{
if $(this) is li
{
add to selection;
}
call searchli($('this'));
}
next element;
return selection;
};

call searchli($('#list'))

i would select via assigning class select or attribute select and querying this in "main" again. so this is basically a recursive function that walks through every child node of the initial selection, even though it will most probably not work exactly that way

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.