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
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()
.
You should do
$(this).parent().attr('data-element')
because you can't call attr()
on a non jQuery object
Try doing this instead:
$(this).parent().attr('data-element');
For more information on functions like .parent() see the Traversing section of the JQuery documentation: http://api.jquery.com/category/traversing/
Using jquery it should be:
$(this).parent().attr('data-element');
Without using jquery this would be:
this.parentNode.getAttribute("data-element")
I prefer to use:
var item = $(this);
var parent = item.closest(".element"); //using the class for selection
//and then use parent.attr('data-element')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.