Use variables in document.querySelector - javascript

If I have:
<div class="test" data-name="Paul" >
and
var name = "Paul";
Can I use document.querySelector to do something like this?
document.querySelector("[data-name=name]");
This doesn't work. What do I have to do?

You can do that, but you need to use the CSS.escape() function to ensure the value is properly encoded for use in a CSS expression.
var name = "hello, world!";
document.querySelector("[data-name=" + CSS.escape(name) + "]");
<div data-name=​"hello, world!">​…</div>
ES2015:
const name = "hello, world!";
document.querySelector(`[data-name=${CSS.escape(name)}]`);
If you don't use CSS.escape(...) then certain values of name could cause your code to throw an error instead.
var name = "hello, world!";
document.querySelector("[data-name=" + name + "]");
Uncaught DOMException: Failed to execute 'querySelector' on 'Document': '[data-name=hello, world!]' is not a valid selector
If you're targeting a browser which doesn't natively support CSS.escape() you can use this polyfill by Mathias Bynens.

You need to concatenate the strings, like:
document.querySelector("[data-name=" + name + "]");
For example:
(See #Jeremy Bank's answer for a much better answer, tho)
var name = "Paul";
var element = document.querySelector("[data-name=" + name + "]");
alert(element.nodeName);
<div class="test" data-name="Paul">
test.
</div>

you could also do this
let name = 'Paul'
document.querySelector('.'+ name)
then you do not need a data-name

This works in Typescript:
document.querySelector(\`[data-name=${name}]`)

<div class="test" data-name="Paul"></div>
Try in this way it may be work :-
var username = "Paul";
document.querySelector(`[data-name="${username}"]`);

I'm super late to this party but check out the code snippet - it shows you how to get the current value of data-name and also how to change the value
let test = document.querySelector('.test');
// get the current value of data-name
let name = test.dataset.name;
console.log('current value of data-name: ' + name)
// change the value of data-name
let newName = 'Jimmy'
console.log(test.dataset.name = newName);
<div class="test" data-name="Paul"></div>

Related

JS: how to filter table using variable

I have a function that I need to use for filtering table rows:
setFilterString("Filter");
But I have a problem. I can set it to
setFilterString("OrderID = 5");
and it will filter out row where OrderID is equal to 5 but if i try using a variable that has a value taken before like this
setFilterString("OrderID = vOrderID");
I get error "Invalid column name 'vOrderID'." (as vOrderID is variable and not a column, I guess)
I have seen somewhere in filter section inputting something like this ("OrderID = '" & vOrderID & "'") but it doesn't have any result at all for me. Doesn't even throw any error in the console.
JavaScript assumes you are just passing a string to the function. If you want to use the variable, you should try this:
setFilterString("OrderID = '" + vOrderID + "'"); // Results in OrderID = '5'
or
setFilterString("OrderID = " + vOrderID); // Results in OrderID = 5
depending on the body of your function.
Use + instead of &: setFilterString("OrderID = " + vOrderID) should work.
Use "+" for merge strings:
setFilterString("OrderID = " + vOrderID)
You can also try to use ${idvOrderID} inside string:
setFilterString("OrderID = ${vOrderID}")
Or:
setFilterString(sprintf("OrderID = %s", vOrderID))
Remember about difference between ' and "

How to modify environment variables using WMI and JavaScript?

I need to access an environment variable and modify its value. I can access the variable using WQL ==>
wmi.ExecQuery("Select * from Win32_Environment Where name='Path' And UserName='<System>'");
However, I am not sure how to modify and save the value. I am using:
var reg = GetObject("winmgmts:/root/cimv2");
var paths = wmi.ExecQuery("Select * from Win32_Environment Where name='AA' And UserName='<System>'");
var items = new Enumerator(paths);
var path = items.item();
path.VariableValue = path.VariableValue + ";" + "random";
path.Put_(); //(as per first answer received)
But, I get this error:
Access denied
Code 80041003
Source SWbemObjectEx
I have UAC disabled, not sure what to do here.
Any help will be appreciated.
Thanks.
After you change the VariableValue, call Put_ to apply the changes:
path.VariableValue = path.VariableValue + ";" + "random";
path.Put_();

Get last string from URL with jQuery

Im trying to get the last string from a URL for example...
http://www.mywebsite/blog/this-post
I want to use jQuery to get 'this-post'
Ive the following...
$('img.gigthumb').each(function(){
var foo = $(this).parent().attr('href').split('/');
$(this).attr('src','/lic/wp-content/uploads/2012/01/'+foo[1]+'.jpg');
})
only it doesn't work and I presume thats because I have multiple '/' within the URL, any idea how to target just the last?
Hope this makes sense!
This is precisely what .pop() is made for:
$('img.gigthumb').each(function(){
var foo = $(this).parent().attr('href').split('/').pop();
$(this).attr('src','/lic/wp-content/uploads/2012/01/' + foo + '.jpg');
});
Don't use the element with index 1 of foo, but the last one:
$(this).attr('src','/lic/wp-content/uploads/2012/01/'+foo[foo.length-1]+'.jpg');
Splitting with "/" will give you the array:
foo[0] = "http:"
foo[1] = ""
foo[2] = "www.mywebsite"
foo[3] = "blog"
foo[4] = "this-post"
If you want to get the last item regardless of the size of the array do:
foo[foo.length - 1]
or as Joseph mentioned: foo.pop()
Following your example you need the last part of the splits:
$('img.gigthumb').each(function(){
var foo = $(this).parent().attr('href').split('/');
var last = foo.length - 1;
$(this).attr('src','/lic/wp-content/uploads/2012/01/'+foo[last]+'.jpg');
})
var foo = $(this).parent().attr('href').replace(/^.*\\/, '');

Unable to concanate String+Variable+String in Javascript

I am trying to dynamically have my javascript look for an element ID in the DOM.
I am currently using this
var string = "retail";
document.getElementById('markup_'+string+'_percentage').value=z.toFixed(2)+"%";
Where the variable "string" has a value like "retail"
This I thought would give a concatenated string of "markup_retail_percentage".
However it actually gives this as an error message:
document.getElementById("markup_"+string+"_percentage") is null
I have tried also using the "." and " * " operators.
One of my html elements
<input type="text" id="markup_retail_percentage" size="5" name="markup_retail_percentage" value="" readonly />
SOLUTION!!!!
//using a new variable name to be passed to function
function percentage(elementid)
{
elementid = "markup_" + elementid;
elementid = elementid + "_percentage";
document.getElementById(elementid).value = "a value";
}
I see two^w three^w four possibilities:
string doesn't contain what you think it does
you should have an underscore before percentage.
the specified element really doesn't exist! (thanks #jAndy)
it does, but the DOM isn't ready yet (thanks #Yoshi)
It looks like you are missing an underscore ahead of percentage
document.getElementById('markup_'+ string +'percentage')
I think you want
document.getElementById('markup_'+ string +'_percentage')
If you run this code before the Document has finished loading, your markup will not have been fully parsed and the Element with that id will not be accessible using DOM methods.
Solution:
function percentage(elementid)
{
elementid = "markup_" + elementid;
elementid = elementid + "_percentage";
document.getElementById(elementid).value = "a value";
}
I dont know why its working:
-Could be concatenation problem , not allowed to use multiple " + " operators?
-Change variable name ?
But it is working now, so thanks to all!

javascript elements not working

I was not able to get part of this javascript code working for unknown reason and display as undefined. How do I merge vote[1] into the formObj which is document.forms[0] Any other alternate solution?
var elements2 = formObj.elements['vote[' + pollId + ']';
There is a basic syntax error:
var elements2 = formObj.elements['vote[' + pollId + ']';
Should be
var elements2 = formObj.elements['vote[' + pollId + ']'];
Could it be that you want:
var elements2 = formObj.vote[pollId];
(Assuming "vote" is the name of several form elements)
You might want to read about how to handle forms in JavaScript.
I'm not a javascript programmer really, but from what I can see above in the code you are missing a "]" at the end of elements.
It looks like your setting elements2 to formObject.elements[i] where you using vote[pollId] as the index. So vote[pollId] should return an integer in this scenario.
I'm not sure if I understand the question
Javascript Arrays
var formObj = document.forms[0];
var i = formObj.length + 1;
formObj[i] = vote[1];

Categories