开发者

Adding li element only if it not already there?

开发者 https://www.devze.com 2023-01-01 07:29 出处:网络
I am constructing an <li> element like this: var element = $(\"<li></li>\") .html(mHTML)

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,

开发者_如何学JAVA<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?


if(!$('#elemul li:contains("Element 1")').length)
{
    $('#elemul').append($('li').attr('id', 'elemli1').text('Element 1'));
}


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
0

精彩评论

暂无评论...
验证码 换一张
取 消