Jitender
Jitender

Reputation: 7971

How to get nodeType using jquery

I want to get nodeType and then compare it to where it is text node or element node.

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="jquery-1.7.2.js"></script>
<script type="text/javascript">
$(function(){
    var mm= $('.jj')
    alert(mm.nodeValue)
    })
</script>
</head>
<body>
<div class="jj">value</div>
</body>

Upvotes: 7

Views: 26571

Answers (5)

Michael Rush
Michael Rush

Reputation: 4340

As noted above, $('.jj').get(0).nodeType works.

Same as $('.jj').first().nodeType

or $('.jj').prop('nodeType')

.prop() : Get the value of a property for the first element in the set of matched elements or set one or more properties for every matched element.

Upvotes: 1

shao.lo
shao.lo

Reputation: 4626

I know it wasn't the question, but to see what type it is (DIV, SPAN, etc), use tagName.

var mm = $('.jj').get(0);
alert(mm.tagName);

Upvotes: 9

VisioN
VisioN

Reputation: 145398

To get the DOM Node you can use [0]:

var mm = $(".jj")[0];
if (mm.nodeType === 1) {
    // Node.ELEMENT_NODE
}

However, <div> element will never be a text node and won't have a nodeValue.

Text node is the first child of your <div> element. So the following code will give you "value":

alert(mm[0].firstChild.nodeValue);

Upvotes: 2

ek_ny
ek_ny

Reputation: 10243

<script type="text/javascript">
$(function(){
    var mm= $('.jj')
    alert(mm.get(0).nodeValue)
    })
</script>

or

<script type="text/javascript">
$(function(){
    var mm= $('.jj')
    alert(mm[0])
    })
</script>

Because a jquery collection is a "wrapped set" of DOM elements.

Upvotes: 1

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123377

try to access to those properties with

var mm = $('.jj').get(0);
alert(mm.nodeValue);
alert(mm.nodeType)

Upvotes: 18

Related Questions