Cómo obtener el tipo de nodo usando 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">
<script type="text/javascript" src="jquery-1.7.2.js"></script>
<script type="text/javascript">
    var mm= $('.jj')
<div class="jj">value</div>

preguntado el 28 de agosto de 12 a las 14:08

5 Respuestas

try to access to those properties with

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

Respondido 28 ago 12, 14:08

@amit get(0) returns the native DOM element from the jQuery object, allowing you to use get the native javascript nodeValue y nodeType properties from it. - Rory McCrossan

porque nodeValue y nodeType are properties of the DOM nodes while $('.jj') devolver un jQuery object, that's why you need to use get() - Fabricio Calderan

nodeValue se mostrarán null desde .jj es siempre un nodo de elemento. - Visión

when i am trying to get nodeValue it give me null, i want to access text of div - Jitender

Can you please share some text node example - Jitender

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

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

respondido 17 nov., 16:03

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

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

Sin embargo, <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":


Respondido 28 ago 12, 15:08

Can you please share some text node and also how to get to know which is element node and which one is text node - Jitender

@amit Here is one option: mm[0].firstChild.nodeValue. - Visión

One last thing i have change my html and i want to select text inside the span <div class="jj">value sdfasfsa <span>jitender</span> </div> - Jitender

@amit To select or to get? In order to get text just use var text = $("span").text();. - Visión

But i want access this through nodes - Jitender

<script type="text/javascript">
    var mm= $('.jj')


<script type="text/javascript">
    var mm= $('.jj')

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

Respondido 28 ago 12, 14:08

Como se señaló anteriormente, $('.jj').get(0).nodeType obras.

Igual que $('.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.

respondido 30 mar '17, 23:03

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.