views:

40

answers:

2

I am constructing an <li> element like this:

var element = $("<li></li>") 
    .html(mHTML)  
    .attr('id', "elemid");

I am trying to add this element to a <ul> element only if it doesn't already exist. Any ideas on how to do this? Am I supposed to use contains() to see if the ul element contain the html and then decide? For instance,

<ul id="elemul">
  <li id="elemli1">Element 1</li>
  <li id="elemli2">Element 2</li>
  <li id="elemli3">Element 3</li>
</ul>

If I try adding Element 1, it should not add it. What should I do if its a longer string (not really long but about 150 characters).

Note: I cannot rely on IDs to determine the uniqueness. i.e. I might end up forming something like: <li id="elemli3">Element 1</li>

Do I go about using hashmaps?

+2  A: 

I am not a jQuery user, so bear with me. However, the native JavaScript can be turned into jQuery code quite easily.

if (!document.getElementById('elemli1')) {
  var elemli1 = document.createElement('li');
  elemli1.id = 'elemli1';
  document.getElementById('elemul').appendChild(elemli1);
}

If you want to create an element if there are no list items in the list at all, replace the if expression with:

!document.getElementById('elemul').childNodes.length
Delan Azabani
@Delan: Thanks for the tip. Sorry that I wasn't clear. The content could come in with a different ID in my case. Just updated my post.
Legend
OK then. Updated my post to have a possibly more helpful answer.
Delan Azabani
+1 for the tip Delan. I am learning jQuery now so I was looking for a more jQuerish approach :) Thanks for your time.
Legend
+2  A: 
if(!$('#elemul li:contains("Element 1")').length)
{
    $('#elemul').append($('li').attr('id', 'elemli1').text('Element 1'));
}
aherrick
This is correct according to the OP's request. Unfortunately, `contains` is close to useless in most cases. It is case sensitive, and you cannot limit it to an whole match; `li:contains("Element 1")` will also get `<li>Element 100</li>`. It is probably better to hold this data in a variable, not in the DOM.
Kobi