How can I get data from multiple attributes? - javascript

I want to get data from multiple attributes on click event. Suppose I have a div with class test_class and ID testID as given below.
<div class="test_class" id="testId"><!-- ... --></div>
I want to get the value of the class and id attributes and store them in separate variables.
var classattr = 'test_class';
var idattr = 'testId';
How can I make this? I would like to avoid calling attr() multiple times.

You can get those with javascript too, like below.
var attrs = document.getElementById("testId").attributes;
var classattr = attrs["class"].nodeValue;
var idattr = attrs["id"].nodeValue;
console.log(classattr);
console.log(idattr);
<div class="test_class" id="testId">
</div>

Even simpler with object destruction:
var t = document.getElementById("testId");
var {className, id} = t;
console.log(className, id)
<div class="test_class" id="testId">
You can add any other attributes between surly braces if you need.

console.log("Div id is "+$('div').attr('id'))
console.log("Div class is "+$('div').attr('class'))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test_class" id="testId"></div>
Use .attr()
Description: Get the value of an attribute for the first element in the set of matched elements.

USE:
$(this).each(function() {
$.each(this.attributes, function() {
// this.attributes is not a plain object, but an array
// of attribute nodes, which contain both the name and value
if(this.specified) {
console.log(this.name, this.value);
}
});
});
You will not have to use .attr multiple times.
For eg: a single span tag with multiple attributes can be obtained using the above code.

what you can do is when a certain button has been pressed. lets say the class btn has been clicked.
<html>
Click me
<div class="test_class" id="testId> Some stuff in here </div>
</html>
<script>
$("").click(function(){
var dvclass = $(".test_class").attr("class");
var dvid = $(".test_class").attr("id");
});
</script>

You don't need jQuery at all. By the magic of vanilla JavaScript, you can already access the class and id of any element you have. There is even a neater interfaces for adding/removing classes: classList. You can use them as follows, in a jQuery click handler:
$('.test_class').click(function() {
console.log(this.className, this.id);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test_class" id="testId">Click me!</div>
Or without any jQuery:
document.querySelector('.test_class').addEventListener('click', function() {
console.log(this.className, this.id);
});
<div class="test_class" id="testId">Click me!</div>
To access other attributes, you can use other methods.
data-* attributes? Use dataset.
name attribute? Well... name.
Attribute that cannot be accessed directly? getAttribute() has you covered.

function getDomNodeProps(domNode) {
let attrs = {}
Array.from(domNode.attributes).forEach(a => attrs[a.name] = a.value);
return attrs;
}
console.log(getDomNodeProps(document.getElementById("testId")))

Try with attr().And do with click function .Then find the attr value using this.attr
$('.test_class').click(function() {
var cls = $(this).attr('class');
var id = $(this).attr('id');
console.log(cls, id)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test_class" id="testId">click</div>

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("div").click(function(){
var clnm=$(this).attr("class");
var idSel=$(this).attr("id");
});
});
</script>
</head>
<body>
<div class="test_class" id="testId">
Example
</div>
</body>
</html>
$("div").click(function(){
var classattr=$(this).attr("class");
var idattr=$(this).attr("id");
console.log(classattr,idattr);
});

$(this).each(function() {
$.each(this.attributes, function() {
// this.attributes returns array
if(this.specified) {
console.log(this.name, this.value);
}
});
});

Related

Is it allowed to use jQuery $(this) selector twice in a function and in an included each loop?

I have a list, which contents x columns of data. When clicking an edit button in a row, I want to set the html content of each column of this row, which has a name attribute into an array, which key is named by the columns name attributes value.
data['id'] = '123';
data['name'] = 'John Doe';
data['city'] = 'Arlington';
For that I'm starting a click event on the edit div. Inside this function I'm working with $(this) selector for setting up an each() loop over all elements having a name attribute.
Inside this loop I'm catching the names and values of each matched element with $(this) selector again.
So, my question: although it works - is it allowed to do it this way? Using $(this) for two different things inside the same function?
Is there a different way?
Here is my working example code
$( document ).ready(function() {
$(document).on( "click", ".edit", function() {
var data = {};
$(this).closest('.row').children('div[name]').each(function() {
//form_data.append($(this).attr('name'), $(this).html());
data[$(this).attr('name')] = $(this).html();
});
$('#result').html(JSON.stringify(data, null, 4));
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row">
<div name="id">123</div>
<div name="name">John Doe</div>
<div name="city">Berlin</div>
<div class="edit">> edit <</div>
</div>
<br clear="all">
<div id="result"></div>
Is it allowed?
It works, so of course.
Depends on what you mean by "allowed".
Is it confusing - perhaps.
Can it cause problems - definitely.
(There are plenty of questions on SO with this or problems caused by this that confirm it causes problems).
Reusing variable names ('this' in this case) is common and is based on scope.
It's hard to tell if you have a bug because you actually wanted the ".edit" html or the ".edit" attr rather than the div, so you can remove that confusion by copying this to a variable:
$(document).on( "click", ".edit", function() {
var data = {};
var btn = $(this); // the button that was clicked
btn.closest('.row').children('div[name]').each(function() {
// Do you mean the div or did you really mean the clicked button?
data[$(this).attr('name')] = $(this).html();
var div = $(this); // the child div
// clearly not what is desired
// `btn` variable referring to the outer `this`
data[div.attr('name')] = btn.html();
// intention clear
data[div.attr('name')] = div.html();
});
$('#result').html(JSON.stringify(data, null, 4));
});
In this case, it's "clear" as you wouldn't use the btn html on all the data entries (or would you? I don't know your requirements...). So "unlikely".
But it's easy to see how, in another scenario, you would want to refer to what was clicked btn==this inside the nested .each.
Try this trick:
$( document ).ready(function() {
$(document).on( "click", ".edit", function() {
var data = {};
var that = this; // trick here
$(this).closest('.row').children('div[name]').each(function() {
//form_data.append($(this).attr('name'), $(this).html());
data[$(this).attr('name')] = $(that).html();// replace this = that if you want to get parent element
});
$('#result').html(JSON.stringify(data, null, 4));
});
});
there is nothing wrong, what you do is simply this
function setDivs() {
//form_data.append($(this).attr('name'), $(this).html());
data[$(this).attr('name')] = $(this).html();
}
function docClick(){
var data = {};
$(this).closest('.row').children('div[name]').each(setDivs);
$('#result').html(JSON.stringify(data, null, 4));
}
function docReady(){
$(document).on( "click", ".edit", docClick)
}
$( document ).ready(docReady);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row">
<div name="id">123</div>
<div name="name">John Doe</div>
<div name="city">Berlin</div>
<div class="edit">> edit <</div>
</div>
<br clear="all">
<div id="result"></div>

How can I check whether element exists based on the classname?

As I mentioned in the title of my question, my element doesn't have id attribute. So how can I check whether it exists or not?
Here is my HTML:
<div class="classname">something</div>
Note1: I can do that if there is a id attribute like this:
var el = document.getElementById("idname");
if ( el ){
console.log("exists");
} else {
console.log("not");
}
But I want to know how can I do that based on the class name .. is it possible?
Note2: I use jQuery.
Vanilla javascript (without jQuery or any other lib):
var els = document.getElementsByClassName('className')
var first = els[0]
Notice that this is an array, since there could be many elements with that class
With jQuery:
var els = $('.className')
this will result in a jQuery object instead of a DOM element, so you better use the length() method for checking existence.
check with .length ,coz className will give you array list if exist
var el = document.getElementsByClassName("classname");
if ( el.length > 0 ){
console.log("exists");
} else {
console.log("not");
}
You need to use getElementsByClassName instead of getElementById.
https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName
If using jQuery, please use class selector.
https://api.jquery.com/class-selector/
Try this:
if($('.classname').length > 0)
{
alert('exist');
}
You could try something like this:
if ($(".classname")[0]){ // do stuff }
This will use the jquery selector to grab all items with that class name, and attempt to access the first result (in position 0). This will fail if there are no elements with this class name.
You can use this:
var el = document.getElementsByClassName("classname");
if (el) {
console.log("exists");
} else {
console.log("not");
}
try this.this will show how to get the class in automatically document.ready or , when a button clicked.
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
<body>
<div class="classname">something</div>
</body>
<script type="text/javascript">
// you can check the class name in document ready or in any other event like click
//this will show all the class names of div when document ready.
$(document).ready(function(){
var the_class_name = $("div").attr('class');
alert(the_class_name); // this put to show you the classs names
if(the_class_name == "classneme")
{
//do your coding
}
else
{
//do your coding
}
});
//if you want to get the class name when a button click and check if the class is exist
$(document).ready(function(){
$("div").click(function(){
var classnames = $(this).attr('class');
alert(classnames);
if (classnames == "your_class_name")
{
// your code here
}
else
{
// your code here
}
});
});
</script>
</html>

Jquery on click not working while passing data

Question is very simple but due to some reason i am not able to fix it.
Here is the a href tag that will open modal box.
<center>Apply</center>
Here is jquery to get id from data attribute.
<script type="text/javascript">
$('document').ready(function()
{
$(document).on('click', '#btn-classified', function() {
//$("#btn-classified").on("click", function () {
//$("#btn-classified").click(function() {
var myvar1 = $(this).data('data');
alert(myvar1);
});
});
</script>
For some reason i am not getting any output if i use $(document).on('click', '#btn-classified', function() {
and if i use $("#btn-classified").on("click", function () { then i am getting undefined.
To get 'data' attribute of <a> element use .attr() function of jQuery
$('document').ready(function() {
$(document).on('click', '#btn-classified', function() {
var myvar1 = $(this).attr('data'); // .attr() to get attribute of an element
alert(myvar1);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href='#' id='btn-classified' data='This an element of DOM'>Get this DATA value</a>
Your Code get undefined on event click when your call to an element which exist after of the function.
You need performance the logic of your code, on jQuery you want use
$(document).ready(function(){
//your functions with selectors of DOM
})
or use .on() function of jQuery to events.
$(document).on('click', '.mainButton', function(){
//your code
})
You have two hrefs - one says javscript:void(); the other has a hash (#) Remove one. Then you won't get undefined.
You'll want to change data to data-id in your HTML. That way you can access the data properties in your javascript like so:
$('#btn-classified').on('click', function() {
alert($(this).data('id'));
});
$(this).data('data') would actually expect data-data="<?=$someId?>" in your HTML.
As per the docs https://api.jquery.com/data/ the attribute should be data-data
if it needs to be fetched through .data function.
$('document').ready(function()
{
$(document).on('click', '#btn-classified', function() {
//$("#btn-classified").on("click", function () {
//$("#btn-classified").click(function() {
var myvar1 = $(this).data('data');
alert(myvar1);
});
});
<script data-require="jquery" data-semver="3.0.0" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.js"></script>
<body>
<center>
<a href="#" class="btn-home" data-data="123" data-toggle="modal" data-target="#ApplyModal" name="btn-classified" id="btn-classified" >Apply
</a>
</center>
</body>
Use .attr('data') instead of .data('data') functions because .data function is used to Store arbitrary data associated with the matched elements or return the value at the named data store for the first element in the set of matched elements.

change the background of an id that is clicked

When one of the element(id) of a form is clicked, i would like to listen to that event, and change the background of that element.
$(document).ready(function(){
$('form').on('click', function(e){
var x = e.target.id;
$(x).css('background-color',color);
return false;
});
}
<form>
<div id="a">Item1</div>
<div id="b">Item2</div>
<div id="c">Item3</div>
</form>
Your code will end up looking for tag names because the selector is
$("b")
If you want to do it the way you have it, you would need to add the missing #.
$("#" + x).css('background-color',color);
But there is no need to look up the element when you already have a reference to is. Use event delegation and this
$('form').on('click', 'div', function(e){
$(this).css('background-color',color);
});
Why bother using e.target? Just update your code to use $(this):
$(function() {
$('form > div').on('click', function(e) {
e.preventDefault();
$(this).css('backgroundColor', color);
});
});
This will work out. Take care of your tags.
$(document).ready(function(){
$('form').on('click', function(e){
var x = e.target.id;
$("#"+x).css('background-color',"red");
return false;
});
});
The thing happening to you is that event.target.id returns a string representing the id of the element, not a selector. So where you use $(x).... you have to use $('#'+x), your actual code does not work because the selector for the background change is not looking for an element with the X value on the Id but for an element called like the value of X (eg. x="a", then it's looking for elements)
Here's my "lowly" try:
<!DOCTYPE html>
<html lang = 'es'>
<head>
<title> My Test </title>
</head>
<body>
<form>
<div id="a"> Item1 </div>
<div id="b"> Item2 </div>
<div id="c"> Item3 </div>
</form>
<script>
function addBackgroundColor(e){
var index = parseInt(Math.random() * 4); // the number of the multiplier has to be equal to the length of the array colorsList.
e.target.style.backgroundColor = colorsList[index];
}
var colorsList = ['blue','red','green','yellow','orange']; //add others colors here if you want.
var divsList = document.getElementsByTagName('div');
for (var i in divsList){
divsList[i].addEventListener('click', addBackgroundColor);
}
</script>
</body>
</html>
No need to go fancy. Just do
$(document).ready(function(){
$('form div').on('click', function(e){
$(this).css('background-color',color);
return false;
});
}

function caller invalid element

If I have :
<div id="mydiv" onmouseover="myfunc()">
<div id="mydiv1"></div>
<div id="mydiv2"></div>
</div>
<script>
function myfunc() {
var evt = window.event || arguments.callee.caller.arguments[0];
var em = evt.target || evt.srcElement;
return em.id;
}
</script>
The function is called by mydiv onmouseover, but if mouse cursor is over mydiv1 function returns mydiv1.
How to make it always to show mydiv?
P.S : I know that I can use something like myfunc(this), but I would like to find caller from inside my function.
Personally I would prefer to use jQuery to hook up the event:
$('#mydiv').on('mouseover',function(){
var id = $(this).attr('id');
// ...
});
If this should be applied to several elements, then use a class selector instead:
$('.hoverable').on('mouseover',function(){
var id = $(this).attr('id');
// ...
});
To also handle future content, attach the event handler to a common ancestor, and select the hoverable elements in the second parameter to on:
$('body').on('mouseover','.hoverable',function(){
var id = $(this).attr('id');
// ...
});
See it in action with future content here.
You should attach the event handler via JavaScript. You can then access the element it is directly bound to as this inside it.
<div id="mydiv">
<div id="mydiv1"></div>
<div id="mydiv2"></div>
</div>
<script>
function myFunc() {
return this.id;
}
var mydiv = document.getElementById('mydiv');
mydiv.onmouseover = myFunc;
</script>
You can do this using Jquery easily.
$('#mydiv').hover(function(){
alert(this.id);
});​​​​​​
Check this : http://jsfiddle.net/shahvj27/6zE96/

Categories

Resources