Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting attribute of a parent node

I am trying to use

$(this).parentNode.attr('data-element')

which should return 0 - 5 in string but it just won't work. I am using it in a function like this

$('.someClass').each(function(){
    $(this).html(SomeFunction('SomeString', $(this).parentNode.attr('data-element')));
});

All the elements with class 'someClass' have a parentNode

<li class="element" data-element: 1 (or any number from 0 to 5 (including))> </li>

and I have no idea where is the mistake. What am I doing wrong?

--David

like image 858
David Debnar Avatar asked Feb 03 '12 09:02

David Debnar


People also ask

How do you find the parent element of a node?

To get the parent node of an HTML element, you can use the parentNode property. This property returns the parent node of the specified element as a Node object. The parentNode property is read-only, which means you can not modify it.

What is the parent node?

A Node that is the parent of the current node. The parent of an element is an Element node, a Document node, or a DocumentFragment node.


1 Answers

You are mixing jQuery and plain javascript in the same line of code and that will not work. You can either use:

$(this).parent().attr('data-element');   // jQuery

or

this.parentNode.getAttribute("data-element");   // plain javascript

parentNode is not a property of a jQuery object, so you can't mix the two the way you were doing it. The jQuery method for getting the parent is .parent().

like image 165
jfriend00 Avatar answered Sep 18 '22 19:09

jfriend00