can we pass a variable to data attribute of html - javascript

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

Related

jQuery: get the normal JS format of a html element

I am using jQuery and everything works fine except a few stuff. There are a few things you cannot do with the jQuery format of an element but only with the simple JS format. Especially, when using the hasAttributes() in simple JS.
This works:
let fooDiv = document.getElementsByTagName("div")[0];
console.log(fooDiv.hasAttributes()); //returns false as expected
let barDiv = document.getElementsByTagName("div")[1];
console.log(barDiv.hasAttributes()); //returns true as expected
<div>foo</div>
<div id="id">bar</div>
This doesn't:
let fooDiv = $(document.getElementsByTagName("div")[0]) //creates a jQ object
console.log(fooDiv.hasAttributes()); //error
let barDiv = $(document.getElementsByTagName("div")[1]) //creates a jQ object
console.log(barDiv.hasAttributes()); //error
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>foo</div>
<div id="id">bar</div>
I am aware that the jQuery hasAttr() exists but I want to get the JS format of a jQuery object. There are a lot of differences, for example the jQuery creates an object but otherwise it is a html node list.
Initially, my question is:
How do I get the html node list or html element or the simple JS format of a html element(s) from jQuery?
To expand on what blex said in the comments ... when jQuery is used to select an HTML element, the raw HTML is always collected in an array as part of the variable you assign it to. For example, using your code:
// grab the element or elements
let fooDiv = $(document.getElementsByTagName("div")[0]);
// lets see the HTML!
consoe.log( fooDiv[0] );
The HTML itself will be exposed in that array, allowing direct access to the HTML and its properties... for example:
console.log( fooDiv[0].innerHTML );
or
console.log( fooDiv[0].tagName );

How to extract an value from an external html page in javascript/jquery

I have a link example this
Now I want to get the source of this page and extract the md5 hash value which is something like
<strong>MD5:</strong> 1b061e5530d2612135b8896482e68e3c</div>
<div>
I want to get the value 1b061e5530d2612135b8896482e68e3c from it.
I have made an GET request and got the source code in an variable like:
$.get(link).done(function(data){
alert(data);
});
This seems to be working fine but I have no Idea how to proceed further kindly help me .
I have Searched but not got any helpful result.
You could use good, old fashioned regexp (i.e., the second result of /MD5:<\/strong> (.*?)<\/div>/g).
var result = (/MD5:<\/strong> (.*?)<\/div>/g).exec([text])[1];
var regex = /MD5:<\/strong> (.*?)<\/div>/g;
var output=document.getElementById("output");
var test="<strong>MD5:</strong> 1b061e5530d2612135b8896482e68e3c</div>";
var matches = regex.exec(test);
output.innerHTML="MD5 is "+matches[1];
<div id="output"></div>
You can use xpath to get the text node containing the MD5 hash value:
$.get(link).done(function (data) {
var md5Node = document.evaluate('//*[#id="app_info"]/div[1]/div[2]/div[2]/div[1]/text()', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
var md5String = md5Node.textContent;
// ...
});
A better XPath
It would be better to find the MD5 text node based on its sibling's value. The XPath would look like
//*[text()="MD5:"]/../text()
Does the div you're trying to get the value from have an ID? If so you could try something like this
$.get(link).done(function(data){ console.log($(data).find("#idofdiv").text()); });
You could also use jQuery's .load function, like this:
$('div#container').load('external-page.html div#md5');

Acessing value of variable in callign method in Javascript

I am learning in javascript and i want to solve this:
var text = "element1";
function OpenOrClose (text){
CKEDITOR.instances.text.getData();
}
I just want to replace text in calling method in function by value of variable text (in this case element1). I also read something about eval('text') and window['text'], but when i tryed to use it like this:
CKEDITOR.instances.eval('text').getData();
It wasn't work.
Thank you for your help
Attributes = items etc.
CKEDITOR.instances[text].getData();

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 wrong with this code in jquery

I am trying to get plain text out of value stored in variable like this
var lb = $(this).attr("htmllabel");
var text = $(this).html(lb);
alert(text);
When the alert popup it give result as object[Object] but I was expecting the actual string after application of the function.
Can anyone help me in this? Thanks.
$(this).html(lb)
This line is setting the html of whatever this is to whatever is stored in lb. It then returns the jquery object for chaining purposes.
If you want the html of this then you just call $(this).html() with no parameter.
Your code on the second line is setting something not getting something ...
Can you include your HTML and the actual data you want in the alert box and this might help shape the answer
Take a look at the documentation for the html method:
http://api.jquery.com/html/#html2
As you can see from the documentation your code is setting the html for this and then returning a jQuery object. What is it that you want to display exactly?
If you're simply looking to get the value of your custom attribute "htmllabel", you can do the following:
var val = $(this).attr("htmllabel");
alter(val);
As a side note; I would suggest naming custom attributes with data-*according to the HTML5 spec like this:
<div data-htmllable></div>
Your can then access the value of the attribute in two ways (jQuery 1.4.3+):
var val1 = $(this).attr('data-htmllabel');
var val2 = $(this).data('htmllabel');
// Outputs same value //
alert(val1);
alert(val2);
I hope this helps!

Categories

Resources