0

I have htmlElement object and I need check it on exists in DOM: It doesn't exist by selector.

$(htmlElement).length // 1 
$(htmlElement)[0].className // k-button k-state-hover 
$(htmlElement)[0].nodeName // LI 
$("li.k-button.k-state-hover").length // 0
Mediator
  • 14,951
  • 35
  • 113
  • 191
  • What is your issue here? – A. Wolff Apr 30 '14 at 11:09
  • What is `htmlElement`, then? @PatsyIssa This isn't a duplicate of that question, the OP isn't asking for a 'more elegant way' to check for an element. – George Apr 30 '14 at 11:09
  • @PatsyIssa not exactly a duplicate if `htmlElement` is a dom element reference – Arun P Johny Apr 30 '14 at 11:12
  • @ArunPJohny But if `htmlElement` is a DOM node, what's wrong with: `if($(htmlElement).length)` ? EDIT: sorry, i see what you mean by 'not exactly a duplicate' even still hard for me to figure out what is OP's issue here, even the question – A. Wolff Apr 30 '14 at 11:15
  • 1
    @A.Wolff I think if it is a dom node then jQuery will not do a dom look up.... try http://jsfiddle.net/arunpjohny/fFq48/3/ - the newly created dom element also returned true – Arun P Johny Apr 30 '14 at 11:18
  • @ArunPJohny Oh ya, of course! My bad! Could be what OP is looking for, not sure http://jsfiddle.net/fFq48/4/ – A. Wolff Apr 30 '14 at 11:20
  • I think OP is asking how to check whether `htmlElement` is attached to the DOM or not. – phuzi Apr 30 '14 at 11:25
  • @A.Wolff Thanks! I forgot about body =( But phuzi ask right to. – Mediator Apr 30 '14 at 11:32

4 Answers4

2

You can check whether the DOM contains htmlElement with

if ($.contains(document, $(htmlElement)){
    // htmlElement is attached to the DOM
}
phuzi
  • 12,078
  • 3
  • 26
  • 50
0
if(htmlElement.length > 0) {
    //Do what you need
}

or

if($('tag').length > 0) {
    //YOUR CODE
}
phuzi
  • 12,078
  • 3
  • 26
  • 50
Bernardao
  • 466
  • 6
  • 23
0

In order to give proper condition you always need to check length of object

i.e if($("li.k-button.k-state-hover").length)

martian
  • 20
  • 5
0

Try with javascript:

var ele =  document.getElementById('yourId');

 or

var ele = document.getElementByTagName('tag name');

if (typeof(ele) != 'undefined' && ele != null)
{
  // exists.
}
Mr.G
  • 3,413
  • 2
  • 16
  • 20