return the data attr in javascript - javascript

This code returns all elements li in html code.
For example:
<li data="2" class="produkt_w_koszyku"><b>Audi A6</b> <span class="cena_w_koszyku">199000 zł</span><span style="float: right; margin-right: 30px;" class="deleteitembasket"><i class="fas fa-times"></i></span></li><li data="3" class="produkt_w_koszyku"><b>BMW i8</b> <span class="cena_w_koszyku">122 zł</span><span style="float: right; margin-right: 30px;" class="deleteitembasket"><i class="fas fa-times"></i></span></li>
I would like him to return the value of the datas attribute to me. so: 2, 3. How can I change this?
var $ul = $(this).parents('ul');
localStorage.setItem('item_id', $ul.html());

You are wanting to loop through the li elements and pull the value of an data attribute out. The comments above provide what you need, but to summarize:
// you may need a more specific selector, but this works for your html snippet
const dataAttrs = $("li").map(function(){
return $(this).attr('data');
}).get().join(',');
// display your data
console.log(dataAttrs);
Also, it best to follow the standard wisdom on data-* attributes, and rather than using simply data doing something such as data-id, data-data, or whatever. See https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes.

$("li.produkt_w_koszyku").map(function(){ return this.getAttribute('data'); }).get().join(',')
Select all the elements, map the parts that you want into an array and join them on comma. You can use getAttribute() to get the attribute off of the DOM Element.

You need to prepend your data holding items with data- so like data-data, data-class, data-... as below
<article
id="electriccars"
data-columns="3"
data-index-number="12314"
data-parent="cars">
...
</article>
Reading the values of these attributes out in JavaScript is also very simple. You could use getAttribute() with their full HTML name to read them, but the standard defines a simpler way: a DOMStringMap you can read out via a dataset property.
To get a data attribute through the dataset object, get the property by the part of the attribute name after data- (note that dashes are converted to camelCase).
var article = document.getElementById('electriccars');
article.dataset.columns // "3"
article.dataset.indexNumber // "12314"
article.dataset.parent // "cars"

Related

Get inner HTML to id and tag

With the following TypeScript code
let inventory: HTMLElement = document.querySelector("dialog[type=inventory]");
I get the following HTML element
<dialog type="inventory">
<button type="button">Exit</button>
<ul>
<li id="Blue">
<name>Blue item</name>
<amount>2</amount>
</li>
<li id="Red">
<name>Red item</name>
<amount>1</amount>
</li>
</ul>
</dialog>
I am trying to get the inner HTML value for amount and a specific id. For example, id="Red" and its <amount> value.
How can this be done with JavaScript?
I tried as follows, but then I cannot select the id for which I want the amount
inventory: HTMLElement = document.querySelector("dialog[type=inventory] > ul > li > amount");
console.log(inventory.innerHTML); // Prints amount 2
I could imagine using querySelectorAll() and looping over the values, but there should be a better solution.
You can add the ID to your selector:
"dialog[type=inventory] > ul > li#Red > amount"
You could also simplify as you don't need all elements in the tree, just the ones that allow for selection.
"dialog[type=inventory] #Red amount"
By utilizing the querySelector method, you can target a specific li element with a specific id, and subsequently access the text within the amount element by using the textContent property.
example :
let inventory = document.querySelector("dialog[type=inventory]");
let element= inventory.querySelector("li#Red");
let amount = element.querySelector("amount").textContent;
As another answerer states, you can add the ID as a requirement when selecting the li element:
dialog[type=inventory] > ul > li#Red > amount
However, since you can only have one element with the same ID on the page at the same time, you can actually simplify this to just
li#Red > amount
This really feels like an XY problem though, where you're asking to do one thing, but really you only need to do this because of some greater overarching problem. Ideally you shouldn't be looking up the contents of your HTML tree to find values like this, because it's super fragile and unreliable (e.g. if you need to change the structure for styling reasons, etc, you now break all of this logic, and TypeScript won't be able to save / warn you about it at all).
A better approach would be to keep a copy of your data model in JavaScript, and then use that to generate the HTML.
It's also worth noting that neither <name> nor <amount> are valid tags in HTML5. You are allowed to create custom tags, but they must contain at least one - character in their names, e.g. <inventory-name> rather than <name>.
const amount = document.querySelector("dialog[type='inventory'] ul #Red amount").innerHTML;
console.log(amount); // Prints "1"

How add ID to HTML href with javascript

I have an HTML like this
<div class="this">
EXP
</div>
I want to add id to <a>. But do not know what to do.
First select your element using something like .getElementsByClassName(). Keep in mind that .getElementsByClassName() returns a NodeList collection of elements, so you'll want to access the first index (or loop over them). You can then simply set the ID with .id, as the ID is merely a property of an element.
This can be seen in the following:
const element = document.getElementsByClassName('this')[0];
element.id = 'element';
console.log(element);
<div class="this">
EXP
</div>
If you want to add this with Javascript, you'll need to use a selector to target your <a> tag and then set the id attribute on it. You can do this by using the querySelector() function or as seen below:
// Find an <a> tag that occurs below a class called "this" and set its id attribute
document.querySelector('.this > a').id = "some-id";
There are many other available functions to handle this through native Javascript and other frameworks, so your milage may vary depending on what you are using.
Example
In this example, we have provided some CSS that should only apply to an element with an id of "test" and we'll run the necessary code to show that the id is being added to the element (as it will be red):
document.querySelector('.this > a').id = 'test';
#test { color: red; }
<div class="this">
EXP
</div>
Add the id attribute to the <a> tag. See the differences of the middle line:
<div class="this">
<a id="expid" href="exp.com">EXP</a>
</div>

How to get the value of inner attribute of an li using jquery?

I have following code in Java script from which i have to need get the value on an inner attribute of <li>.
<li class="selected" data-val="1">
I have get the tag using
var a = document.getElementsByClassName('selected');
it is providing me <li> whole tag that is fine. But i have to need get the value of data-val attribute (which is within the <li>) that is 1.
How can i get the value of data-val using variable a that is defined.
Please explain..
Here a is a collection object so you need to get the element reference using index then use .getAttribute() to get the attribute value()
var a = document.getElementsByClassName('selected');
var val = a? a[0].getAttribute('data-val') : '';
//another option for modern browsers
// val = a[0].dataset.val
Since you have jQuery, you can use jQuery to select the element and then use data api like
var val = $('.selected').data('val')
With jQuery you can use $(a).attr("data-val").
Without jQuery you can use a.getAttribute("data-val")
Try this approach
var dataValValue = $(".selected").attr("data-val");
It will get data-val attribute from first li from all li with class .selected
There are two ways, using jQuery and the first returned element in a:
$.data(a[0],"val");
$(a[0]).data("val");
Both are equivalent. Sorry, they're not equivalent, since the first one is lower level, and does not process data-* attributes by itself.
There's no need to use .attr() since data-* attributes are processed automatically in the case of the second one.

Custom attribute Not fetchable from li

I have following Code/Structure, what I am trying to do is to hide a div if a custom attribute matches. The problem at the moment is that I can't get the custom attribute as demonstrated in this code:
var elementToHide = 'file_type';
jQuery('#search-img-ctrl').each(function() {
var locationli = jQuery(this).find('li').attr(elementToHide);
alert(locationli);
alert(elementToHide); // I can't get the custom attribute
if (locationli != elementToHide) {
jQuery(this).find('.search-img-box').hide();
} else {
jQuery(this).find('.search-img-box').show();
}
});
And following is my HTML Structure.
<div id="search-img-ctrl" class="search-img-ctrl">
<div class="sampages" style="display: block;">
<div class="search-img-box sampageitems">
<a href="image_detail.php">
<img id="imageimage_array" width="277" height="206" src="upload/2014-05-02-14-05-512014-04-08-14-04-40000560_d.png" alt="">
</a>
<br>
<ul>
<li> Name </li>
<li>upload/2014-05-02-14-05-512014-04-08-14-04-40000560_d.png</li>
<li>identity </li>
<li>Modify</li>
<li latitude="null">Latitude</li>
<li>null</li>
<li longitude="null">Longitude</li>
<li>null</li>
<li model="null">model</li>
<li>null</li>
<li file_type="png">model</li>
<li>png</li>
<li> Image Size </li>
<li>11Kb</li>
</ul>
</div>
</div>
Ideally under html5 you should suffix your custom attributes with data- prefix. However, in your code to find the li that has specific attribute, use:
var locationli = jQuery(this).find('li[' + elementToHide + ']');
Here is a JSFiddle demonstrating this: http://jsfiddle.net/wANxV/
The main wrapper have id and class same value. This is not a good.
Put a numer or other after your id value (id="search-img-ctrl-1" etc) , then do each cycle on class not on id
JQuery.each('.search-img-ctrl');
Put attributes in your markup with 'data' prefix (as Satpal said) and other thig you can use directly the selector
var locationli = jQuery(this).find("li["+elementToHide+"]");
This code reads the attribute of the first found element, but it does not filter on it:
var locationli = jQuery(this).find('li').attr(elementToHide);
A filter might look something like this:
var locationli = jQuery(this).find('li')
.filter(function(){
return $(this).attr(elementToHide);
});
But obviously closure's method is much shorter. And keypaul is right, using data- prefix is the right way to store your own metadata on elements.
the answers to use li[' + elementToHide + '] are good ones, but to help you understand what you are experiencing
let's break down this line of code:
var locationli = jQuery(this).find('li').attr(elementToHide);
as you know, jQuery(this).find('li') returns all of the decendants of this which are li's, and in your example, there are 14 of these.
What does .attr() return when applied to a set of 14 elements?
I guess it could return an array, a concatenation, who knows?, but the writers of jQuery decided to just return the attribute corresponding to the first element in the set. In this case, you are calling .attr(elementToHide) on <li>Name</li>. This element does not have the "file_type" attribute, therefore, you get an empty string in return.
Here's a quick fiddle to illustrate: http://jsfiddle.net/pmn4/B9bqK/
to solve your problem, use either the techniques described by #keypaul and #closure or use jQuery's filter method

How to find an element with a data attribute with unknown value?

I'm looking for a specific element which contain a known data attribute. The actual value of the data could be anything. Example:
<div id="myObject">
<div>
<span data-some-data="anything">something</span>
</div>
<div>
I'm trying to access the span tag in the above example.
I've tried something like:
var $theElementINeed = $('#myObject').find("[data-some-data='" + ??? + "']");
But the value could be anything. So I don't know how to find the span. Any suggestions?
If you just want to check for the existence of the attribute then use the has attribute selector
var $theElementINeed = $('#myObject').find("[data-some-data]");
Per this! discussion, try:$('element').find('[data-some-data]');

Categories