How to get whats inside a variable ID or Class - javascript

Say I have this:
var name = $('#contactName');
Is there a way to get just the contactName out of that variable?
Edit: The variable is already set and the value of it is $('#contactName').
What I want to do is retrieve the text from that variable, not create multiple variables. I could easily duplicate variables and just do var nameID = 'contactName' but I am hoping theres an alternative.

You can use the selector property:
var name = $('#contactName');
alert(name.selector); // alerts #contactName
However, you'd have to strip the #, so something like:
s.selector.replace('#','')
Obviously, this would only work for ID-based or tag-based selectors. Class-based selectors would need the . removing.

Try
var name = $('#contactName').attr('id');

All jQuery objects have a selector property that will return the selector they were created with, so your name object would return #contactName. You could then strip off the hash sign.

The title and body of your question seem at odds.
To answer the title:
If the jQuery object was created with a selector, then name.selector should do the trick.
To answer the body:
name.attr('id')

Don't you just use
var name= $("#contactName").val()
??

Related

Why does my function return undefined, especially the .split()parts?

So in essence I get the value of input, then try to divide into into different tags via the comma with this
var noteTags = document.getElementsByClassName("noteTag").value;
Tag = noteTags.split(",");
But in console, the split(",") is undefined
Edit: Sorry I forgot to mention that the noteTag element is input, does this change how the code works in any way?
There are two issues,
getElementsByClassName returns an array-like collection of elements (a NodeList).
And instead of value it should be innerText.
Try like below
var noteTags = document.getElementsByClassName("noteTag")[0].innerText;
Tag = noteTags.split(",");
You are using the split() method on an array. You are also trying to access the value property, whereby you should probably use innerText.
You can use querySelector then you dont need using a key[0] to select the element.
const noteTags = document.querySelector("#noteTag");
console.log(noteTags)
Tag = noteTags.innerHTML.split(",");
console.log(Tag)
<div id="noteTag">en,jp,fr</div>

jQuery: easier way to use .clone() than described below?

If you execute in the console on this page
var cloned = $(".question").clone(true);
$(".question").addClass("first");
var clonedStr = cloned[0].outerHTML || new XMLSerializer().serializeToString(cloned[0]);
$(".question").after(clonedStr);
you will clone the question (there will be two questions on the page, but the first one will be with the .first class). That's what is needed.
Is there any simpler way to do this with jQuery? I'm confused of the third string in the code above and believe it could be simpler. Any ideas?
Thank you.
If you don't use the HTML as string, then don't get it. Just use the jQuery object:
var cloned = $(".question").clone(true);
$(".question").addClass("first").after(cloned);
Also, you can do it one line:
$(".question").after($(".question").clone(true)).first().addClass("first");
You could use insertAfter to insert the cloned element after changing the class. You don't need to convert the element in the jQuery object to a string, you can use that object within the function itself:
var $question = $('.question');
var $cloned = $question.clone(true).insertAfter($question);
$question.addClass('first');

attach every div to Javascript variable

I know a DIV can be attached to a Javascript variable with code like this:
var targetDiv = jQuery('#targetDiv');
However, I am looking for a way to attach ALL the DIVs or ones of a certain class to Javascript variables.
So, if I have the following elements:
<div id='bozo'>
<div id='ranger'>
<div id='smokey'>
I will end up with the variables:
bozo
ranger
smokey
I've been building lots of jQuery apps and they often have many divs that need to be kept track of in my code. I want to find an easier way to get control of these divs than assigning them to variables at the beginning of my app.
Either a jQuery or Javascript solution would be fine.
The most effective way would be to use a JavaScript object.
var divs = {};
$("div").each(function() {
if ($(this).attr('id') !== undefined) {
divs[$(this).attr('id')] = $(this);
}
});
With your current HTML, the divs could then be accessed like so:
divs["bozo"].show(0);
divs["ranger"]show(0);
divs["smokey"].show(0);
You can't name the JavaScript variables directly after the div IDs, because they have different naming conventions. For example, test-div is a valid ID for an HTML element, but not for a JavaScript variable.
However, if an ID just so happens to be a valid JavaScript variable name, then it can be accessed as a mnemonic property of the object:
divs.bozo.show(0);
divs.ranger.hide(0);
See this demo.
Edit: Added functionality to detect when the div has no ID, based on suggestions from icktoofay and ABFORCE.
I think there is no need to assign every jQuery object to a javascript variable/object. Because the jQuery syntax is very very easy to use.
You can refer to a html element so easy with jQuery, like this:
$("div") // all div elements
$("div#foo") // div with id="foo"
$(".foo") // all element which have 'foo' class
However if your want to assign to a JS object use this:
var obj = new Object() // or = {};
$("div[id]").each(function(){
obj[$(this).attr("id")] = $(this);
});
You can "...access those variables without executing any code, as browsers put elements with an id attribute into the global scope on their own." According to Blender's findings in the comment below. So one can access those variables by the div's IDs as demonstrated here:
http://jsfiddle.net/xhWwH/2
EDIT: Kept my previous answer for reference purpose.
Although I do not agree with this type of programming (very unsafe!!!!). I believe this is what you are looking for: http://jsfiddle.net/haoudoin/xhWwH/
$("div").each(function(index) {
console.log(this.id);
eval("" +this.id + "=this;");
});
console.log("creates: " + bozo);
console.log("creates: " + ranger);
console.log("creates: " + smokey);
// reference to your div
alert(bozo.id);;

html "data-" attribute as javascript parameter

Lets say I have this:
<div data-uid="aaa" data-name="bbb", data-value="ccc" onclick="fun(this.data.uid, this.data-name, this.data-value)">
And this:
function fun(one, two, three) {
//some code
}
Well this is not working but I have absolutely no idea why. could someone post a working example please?
The easiest way to get data-* attributes is with element.getAttribute():
onclick="fun(this.getAttribute('data-uid'), this.getAttribute('data-name'), this.getAttribute('data-value'));"
DEMO: http://jsfiddle.net/pm6cH/
Although I would suggest just passing this to fun(), and getting the 3 attributes inside the fun function:
onclick="fun(this);"
And then:
function fun(obj) {
var one = obj.getAttribute('data-uid'),
two = obj.getAttribute('data-name'),
three = obj.getAttribute('data-value');
}
DEMO: http://jsfiddle.net/pm6cH/1/
The new way to access them by property is with dataset, but that isn't supported by all browsers. You'd get them like the following:
this.dataset.uid
// and
this.dataset.name
// and
this.dataset.value
DEMO: http://jsfiddle.net/pm6cH/2/
Also note that in your HTML, there shouldn't be a comma here:
data-name="bbb",
References:
element.getAttribute(): https://developer.mozilla.org/en-US/docs/DOM/element.getAttribute
.dataset: https://developer.mozilla.org/en-US/docs/DOM/element.dataset
.dataset browser compatibility: http://caniuse.com/dataset
If you are using jQuery you can easily fetch the data attributes by
$(this).data("id") or $(event.target).data("id")
The short answer is that the syntax is this.dataset.whatever.
Your code should look like this:
<div data-uid="aaa" data-name="bbb" data-value="ccc"
onclick="fun(this.dataset.uid, this.dataset.name, this.dataset.value)">
Another important note: Javascript will always strip out hyphens and make the data attributes camelCase, regardless of whatever capitalization you use. data-camelCase will become this.dataset.camelcase and data-Camel-case will become this.dataset.camelCase.
jQuery (after v1.5 and later) always uses lowercase, regardless of your capitalization.
So when referencing your data attributes using this method, remember the camelCase:
<div data-this-is-wild="yes, it's true"
onclick="fun(this.dataset.thisIsWild)">
Also, you don't need to use commas to separate attributes.
HTML:
<div data-uid="aaa" data-name="bbb", data-value="ccc" onclick="fun(this)">
JavaScript:
function fun(obj) {
var uid= $(obj).attr('data-uid');
var name= $(obj).attr('data-name');
var value= $(obj).attr('data-value');
}
but I'm using jQuery.
JS:
function fun(obj) {
var uid= $(obj).data('uid');
var name= $(obj).data('name');
var value= $(obj).data('value');
}
you might use default parameters in your function
and then just pass the entire dataset itself, since the
dataset is already a DOMStringMap Object
<div data-uid="aaa" data-name="bbb" data-value="ccc"
onclick="fun(this.dataset)">
<script>
const fun = ({uid:'ddd', name:'eee', value:'fff', other:'default'} = {}) {
//
}
</script>
that way, you can deal with any data-values that got set in the html tag,
or use defaults if they weren't set - that kind of thing
maybe not in this situation, but in others, it might be advantageous to put all
your preferences in a single data-attribute
<div data-all='{"uid":"aaa","name":"bbb","value":"ccc"}'
onclick="fun(JSON.parse(this.dataset.all))">
there are probably more terse ways of doing that, if you already know
certain things about the order of the data
<div data-all="aaa,bbb,ccc" onclick="fun(this.dataset.all.split(','))">

What is the jQuery alternative to not(':not( selector )')?

What is the jQuery alternative to not(':not( selector )')?
Basically lets say this:
var buttons = $('a.buttons');
I am looking for a particular button with the href as '#measurement' and need to add a class to it. The only way I know how to do this is with not(':not( selector )').
buttons.not(':not([href="#measurement"])').addClass('selected');
There has got to be a better way.
.is() // returns boolean
.has() // looks for items inside each element
Any thing out there?
I believe you want filter:
$elements.filter(selector)
so if you already have
var $buttons = $('a.buttons');
you can get the right one by
var $theButtonIWant = $buttons.filter('[href*="#measurement"]');
The 2 nots cancel out, and you get
$('a.buttons[href="#measurement"]').addClass('selected');
Docs: http://api.jquery.com/category/selectors/attribute-selectors/
EDIT: If you already have a collection, use .filter
var buttons = $('a.buttons');
buttons.filter('[href="#measurement"]').addClass('selected');
var button = $('a.buttons[href*="#measurement"]').addClass('selected');
The [ ] block lets you specify an attribute. The *= operator in it specifies that the attribute contains the quoted text.

Categories

Resources