Getting attribute of a parent node - javascript

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')

Related

How to find class of an dynamic created object by js?

I have an element div which is created by js, i want to get it class.
I try to getElementsByClassName('lt-label')(it works), than i want to check if lt-label has class lt-online and if it true the another block on the page is block.
My code:
$(document).ready(function() {
if (document.getElementsByClassName) {
var redTags = document.getElementsByClassName('lt-label');
if (redTags.is(".lt-online")) {
$("#l-b-wrapper").css({
'display': 'block'
});
};
};
});
But it doesn't work. Where i have mistake?
I give a link only because the html code is big and i can't show my problem full .Site http://www.zemelushka.ru/test/
lt-label - is a right page widget button
l-b-wrapper - left page widget button
You are mixing native and jQuery, Use jQuery object since document.getElementsByClassName will return you an array-like object and they don't have jQuery methods
$(document).ready(function() {
if ($('.lt-label').is(".lt-online")) {
$("#l-b-wrapper").css({
'display': 'block'
});
};
});
You have a really odd mix of native JS and jQuery which is causing the problem.
getElementsByClassName returns an array of DOMElements which do not have the is() method. If you use jQuery to select your elements you can both avoid the problem and shorten your code:
$(function() {
if ($('.lt-label').hasClass('.lt-online')) {
$("#l-b-wrapper").show();
}
});
Note that if there are multiple .lt-label elements found you may need to loop over them, depending on the behaviour you require.
To work with jquery methods you need jQuery Object otherwise you'll get error: method is undefined. So, you may also wrap javascript object with jquery like this:
if ($(redTags[0]).is(".lt-online")) {
Where, redTags is wrapped by jQuery ie. $() and we use [0] for first element as getElementsByClassName result array-like object.
But I would choose simply jQuery object while I work with jquery for simplicity:
$('.lt-label') instead of document.getElementsByClassName('lt-label');
As you should know jQuery has it's own dictionary of methods and it works only with jQuery objects. And you are trying to bind a jQuery method .is() to a dom object which causes in error because .is() is available only for jq objects.
So this would do it (creating a jq wrapper):
$(redTags).is(".lt-online")
and you can shorten it like:
$(document).ready(function() {
var redTags = $('.lt-label');
$("#l-b-wrapper").css({
'display': function(){
return redTags.is(".lt-online") ? "block" : "none";
}
});
});
If you just want to show/hide the element then you can use .toggle(boolean) method:
$(document).ready(function() {
var redTags = $('.lt-label');
$("#l-b-wrapper").toggle(redTags.is(".lt-online"));
});

How can I combine these jQuery statements?

I have a jQuery statement like this;
var current = $(this);
current.hide();
current.siblings('.ab').hide();
current.siblings('.cd').hide();
I want to change this into a single statement and I wrote;
$(current,current.siblings('.ab'),current.siblings('.cd')).hide();
But ab is not hiding. How can I combine the 3 hide() statements into one?
You can use a multiple selector and addBack():
$(this).siblings(".ab, .cd").addBack().hide();
addBack() will add the original element back into the set, so you can get both the element and its relevant siblings in the same jQuery object.
You can use a multiple selector (comma separated) for the siblings function and than use addBack to include the first element.
Add the previous set of elements on the stack to the current set,
optionally filtered by a selector.
Code:
current.siblings(".ab, .cd").addBack().hide();
Try to use .end(),
current.siblings(".ab, .cd").hide().end().hide();
or use .add() like below,
current.add(current.siblings(".ab, .cd")).hide();
try this:
var current = $(this);
current.hide().siblings('.ab').hide().end().siblings('.cd').hide();
You can use comma separated multiple selectors in .siblings()
current.siblings('.cd,.ab').addBack().hide();
Working Demo

Using jQuery, how to specify with the `.attr` method, the second of two html classes?

When using jQuery and are using the .attr method as follows:
$(document).ready(function(){
$('.class1').click(function(){
id = $(this).attr('.class2');
});
});
Say I have the following HTML for the above function:
<div class="class1 $class2"></div>
The second class is attributed at runtime, so I have 10 divs, each with class1, but several with class2. Then I wish to use the jQuery function at the top, so that whenever I click on any of the divs, it applies the specific class2 of that div, to the variable ID.
I hope this makes more sense.
Since your class2 comes from your PHP code, you seem to hit the usecase of data-attributes.
With data-attributes you can easily have some extra data (often used for javascript purposes) on your HTML elements without having to use special classes or ids for that.
It works like that:
<span data-hero="batman">I'm a Bat!</span>
Where in your Javascript (using jQuery) you get the value of it by simply doing:
$('span').data('hero');
Refer to the MDN and the jQuery documentation for further information.
Is this what you're trying to do?
$(document).ready(function(){
$('.class1').click(function(){
var id = $(this).attr('class').replace('class1','').trim();
});
});
If you have a multi class tag this mean the HTML code would be like this:
<sometag class="class1 class2">...</sometag>
I think the simplest approach is to do some string operations on the class attribute of the tag:
var class2 = $(selector).attr("class").split(" ")[1];
OR you can write a simple jQuery plugin to do the work for you:
(function($){
$.fn.secondClass = function(){
var c = this.attr("class").split(" ");
if(c.length >= 2)
return c[1];
};
}(jQuery))
Usage: var class2 = $(selector).secondClass();
Hope this helps.

Using javascript to set an HTML class name

Is it possible to put a javascript function call in place of a HTML class name so that the class can be set based upon the results of the function? For example, something like:
<a class="fSetClass(vName)" ....
which would call a function named fSetClass() and receive back a valid CSS class name based upon the parameter vName passed with it.
Thanks
No, it's not possible to do what you're asking from within the HTML. Though, you can use JavaScript to add the class to it afterward.
Smth like this, if in short way
document.onload = function(){
document.getElementById('your-element-id').className = fSetClass(vname);
}
No but what you can do is use jquery to get the item and then add or remove class names from it:
HTML
<div class="my-class">My Content</div>
jQuery
// will produce <div class="my-class added-class">My Content</div>
var addClass = 1;
if(addClass == 1) {
$(".my-class").addClass("added-class");
}
else
{
$(".my-class").removeClass("removed-class");
}
Only the on* event handler attributes are evaluated as JavaScript code, the other attributes are not.
As already said, you have to assign the class normally with JavaScript. Assuming you have a reference to the element (element), you have to assign the class to the className [MDN] property:
element.className = fSetClass(vname);
If you use jquery, you can set the class by using .attr():
$(document).ready(function() {
function fSetClass(vName){
$("#element_id").attr('class', vName);
}
fSetClass('className');
});
If you use jQuery, you can use the addClass function
$(element).addClass('add-this-class');
If you want to set the class instead, use attr:
$(element).attr('class','add-this-class');

How to clear all <div>s’ contents inside a parent <div>?

I have a div <div id="masterdiv"> which has several child <div>s.
Example:
<div id="masterdiv">
<div id="childdiv1" />
<div id="childdiv2" />
<div id="childdiv3" />
</div>
How to clear the contents of all child <div>s inside the master <div> using jQuery?
jQuery's empty() function does just that:
$('#masterdiv').empty();
clears the master div.
$('#masterdiv div').empty();
clears all the child divs, but leaves the master intact.
jQuery('#masterdiv div').html('');
Use jQuery's CSS selector syntax to select all div elements inside the element with id masterdiv. Then call empty() to clear the contents.
$('#masterdiv div').empty();
Using text('') or html('') will cause some string parsing to take place, which generally is a bad idea when working with the DOM. Try and use DOM manipulation methods that do not involve string representations of DOM objects wherever possible.
I know this is a jQuery related question, but I believe someone might get here expecting a pure Javascript solution. So, if you were trying to do this using js, you could use the innerHTML property and set it to an empty string.
document.getElementById('masterdiv').innerHTML = '';
jQuery recommend you use ".empty()",".remove()",".detach()"
if you needed delete all element in element, use this code :
$('#target_id').empty();
if you needed delete all element, Use this code:
$('#target_id').remove();
i and jQuery group not recommend for use SET FUNCTION like .html() .attr() .text() , what is that? it's IF YOU WANT TO SET ANYTHING YOU NEED
ref :https://learn.jquery.com/using-jquery-core/manipulating-elements/
If all the divs inside that masterdiv needs to be cleared, it this.
$('#masterdiv div').html('');
else, you need to iterate on all the div children of #masterdiv, and check if the id starts with childdiv.
$('#masterdiv div').each(
function(element){
if(element.attr('id').substr(0, 8) == "childdiv")
{
element.html('');
}
}
);
The better way is :
$( ".masterdiv" ).empty();
$("#masterdiv div").text("");
$("#masterdiv > *").text("")
or
$("#masterdiv").children().text("")
$('#div_id').empty();
or
$('.div_class').empty();
Works Fine to remove contents inside a div
You can use .empty() function to clear all the child elements
$(document).ready(function () {
$("#button").click(function () {
//only the content inside of the element will be deleted
$("#masterdiv").empty();
});
});
To see the comparison between jquery .empty(), .hide(), .remove() and .detach() follow here http://www.voidtricks.com/jquery-empty-hide-remove-detach/
When you are appending data into div by id using any service or database, first try it empty, like this:
var json = jsonParse(data.d);
$('#divname').empty();
$("#masterdiv div[id^='childdiv']").each(function(el){$(el).empty();});
or
$("#masterdiv").find("div[id^='childdiv']").each(function(el){$(el).empty();});
try them if it help.
$('.div_parent .div_child').empty();
$('#div_parent #div_child').empty();

Categories