Using queryselectorall with classes - javascript

I have a line <div class="price-box price-final_price" data-role="priceBox" data-product-id="176"> in a large html file.
I need to store the value of product-id inside a variable, so that I can access it globally.
I'm tring to do it with
var var_productid = document.querySelectorAll('div[data-role="priceBox"]')[0].data-product-id;
But it's not working. What am I doing wrong?

If you want to use pure javascript you can use the .getAttribute() method
var var_productid = document.querySelectorAll('div[data-role="priceBox"]')[0].getAttribute('data-product-id');
if you want to use jquery, you can do this
var var_productid = $('div[data-role="priceBox"]').eq(0).attr('data-product-id');

If you intend to use and retrieve data_attributes in javascript, you need to use dataset instead of only data. Also to get product-id, you need to use camel case
var var_productid = document.querySelectorAll('div[data-role="priceBox"]')[0].dataset.productId;
console.log(var_productid)
<div class="price-box price-final_price" data-role="priceBox" data-product-id="176"></div>

var productId = $("div[data-role='priceBox']").attr('data-product-id');

dataProductId = document.querySelectorAll("div")[0].getAttribute("data-roduct-id");

Use getAttribute
No need to use querySelectorAll if you only want the first item found, just use querySelector
Snippet:
var productid = document.querySelector('div[data-role="priceBox"]').getAttribute('data-product-id');

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>

can we pass a variable to data attribute of html

So far I know that we can store data in html element by using:
<div data-test="hello">
$.("div").data("test")
However , I just can store raw text for data attribute
what I need is:
var t= hello
<div data-test=t>
but when I tried this , it shows the letter t instead of hello.
Actually you are changing not the attribute but an property of the DOM object. For data JavaScript has it's own mechanism to hold data for the elements. For more take a look on Documentation.
You can change the data using jQuery (as you have already used it). Use data function and pass your variable as the second argument to the function like $("#d").data("test", t);
console.log($("#d").data("test"));
const t = 'hello';
$("#d").data("test", t); // <- second parameter
console.log($("#d").data("test"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="d" data-test="test">
You can use the attr() function of JQuery instead of data()
var t= 'hello';
$("div").attr("data-test",t);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-test=t>asd
Without jQuery
jQuery is definitely unnecessary in this case. You can achieve the same thing with this code
HTML
<div data-test="hello">
JS
const textToChange = 'other text';
const divWithDataAttribute = document.querySelector('[data-test]');
diveWithDataAttribute.dataSet.test = textToChange;
Conclusion
This will apply the new result to the data attribute and we didn't need jQuery.
A thing to note is the part dataSet.test this part comes from the data-test attribute. We drop the data- part and camel case the rest of the words.
For example data-test-new-test="whatever" becomes testNewTest when accessing the dataSet.
yes you can try this:
$("div").attr("data-test", "test");
var t="hello";
$("div").attr("data-test",t);

How do I get multiple jquery attr values?

My code:
http://codepen.io/vincentccw/pen/ecJDG
Basically what I want to get are all the data attribute values from the attr call data-designer
There are suppose to be 4 of them but I can only get the first one using:
var dsad = $('ul').attr("data-designer");
How do I fix this?
You can use each() to interact with each element individually:
$('ul').each(function(){
console.log($(this).data('designer'));
});
Or you can use map() to create an array of all the values which you can deal with separately:
var designers = $('ul').map(function() {
return $(this).data('designed');
});
console.log(designers);
Note, I used data to get the data-* attributes as this is quicker than accessing the attributes of the DOM element directly.
$('ul').each(function(){
console.log($(this).attr('data-designer'))
//you can add to an array also
});
You can use map() to project the attribute values into an array:
var designers = $("ul").map(function() {
return $(this).attr("data-designer");
}).get();
You need to use .each()
$('ul').each(function(){
console.log($(this).attr("data-designer"));
});
Codepen Demo
$('ul').attr("data-designer") just got the attribute for the first ul element. If to get all uls with "data-designer" attribute, try this:
$('ul[data-designer]').each(function(){
console.log($(this).attr("data-designer"));
});

How to call ID through local Variable

if am having html
<TableView id=img1></TableView>
<TableView id=img2></TableView>
normally
$.img1.backgroundImage = "/Picture1.jpeg"
but I want to know how to store the id in local variable and call the same function, in place of img1 I have to use local variable. is any possibility of this.
Normally $.img1.backgroundImage = "/Picture1.jpeg" would be nonsense since jQuery doesn't populate itself with properties referencing all elements with ids on a page.
Converting that to use a variable instead of an identifier (let's say var foo = 'img1'; for the benefit of all the following examples) would be
$[foo].backgroundImage = "/Picture1.jpeg";
(That's equivalent to the original code, but since I wouldn't expect the original to work, this won't either).
To actually set the backgroundImage property in JS you would:
document.getElementById(foo).style.backgroundImage = "url(/Picture1.jpeg)";
or if you are being a jQuery junkie:
jQuery('#' + foo).css('background-image', 'url(/Picture1.jpeg)');
Yes Sure but need to adjust the code accordingly to set the background image
var img1 = $("#img1")
img1.css("background-image","/Picture1.jpeg");
var images = $("#img1");
or also you can use
var images_obj=form_name.element_name;
var yourVar= $("#img1").attr("id");
I think you want to change the background image css property of an element selected by id, who is in a local variable?
var yourid = "img1";
$('#' + yourid ).css('background-image', '/Picture1.jpeg');
You better save the object instead of id as you would need to get element by id again and again.
var img1Obj1 = $('#img1'); //jQuery object
var img1Obj2 = $('#img1')[0]; // DOM javascript object

How to get whats inside a variable ID or Class

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()
??

Categories

Resources