Access Global data-* attributes in javascript [duplicate] - javascript

This question already has answers here:
How can I get the data-id attribute?
(17 answers)
Closed 3 years ago.
Im trying to write a little filter script for a ajax-table and im trying to open a overlay when someone clicks on the element:
<div class="at-filter" data-filter-val="{some_value}" data-filter-type="{some_type}">
...
</div>
How do i access the data-filter-type and value via javascript/jquery? Cant find anything at all via google.
Something like this is what im looking for:
this.table.find( '.at-filter' ).each(
function(index, element) {
var type=$(element).data-filter-type();
var val=$(element).data-filter-val();
self.data.filter[type] = {};
$(element).bind('click', {self:self, val:val, type:type}, type.openContextMenu);
}
)
edit: Mistakes were made!

To get attrbiute value use jquery attr() or in plain JavaScript getAttribute
But
To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the .prop() method.
Or
In plain JavaScript setAttribute
console.log($('.me').attr('data-attribute'));
console.log($('.me').attr('data-second-attr'));
$('.me').each(function() {
console.log(this.getAttribute('data-attribute'));
console.log(this.getAttribute('data-second-attr'));
this.setAttribute('data-second-attr', 'foo-bar');
console.log('after change', this.getAttribute('data-second-attr'));
})
$('.me').prop('data-attribute', 'baz')
console.log('after change', $('.me').prop('data-attribute'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="me" data-attribute="foo" data-second-attr="bar">yo</div>

You use attr:
var type = $(element).attr("data-filter-type");
You could also use data:
var type = $(element).data("filter-type"); // Read the note below, though
... but it isn't necessary or really appropriate if all you want to do is access the values of those attributes. Contrary to popular belief, data is not an accessor for data-* attributes. (It's both more and less than that.)

Related

Using jQuery variable as HTML attribute [duplicate]

This question already has answers here:
JQuery Update data- attribute/value
(3 answers)
Closed 4 years ago.
You're probably going to tell me to just do this all in jQuery, but I'm asking anyway.
I have an animation library that uses a counter to count from 0 to X. This was part of an HTML template I don't really want to modify.
I have built an AJAX script to GET the data I need to count to from a RESTful API source. Yes, I know, the api-key (secret) is still there, but there's no sensitive data and I'll cycle it after we're done here.
This HTML properly displays the value, but I can't for the life of me figure out how to get the value of the jQuery var $numClients into the "data-to" attribute.
Can anyone help me figure this out? I was hoping I could just reference the variable like "data-to=$varFromQuery" but I am a backend guy, not a JS guy, so I'm totally lost on this.
$(document).ready(function() {
$.ajax({
url: "https://path.to.url"
}).then(function(data) {
$('.totalTransferredGB').append(data.totalTransferredGB);
$('.numClients').append(data.numClients);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div class="counter-item">
<span class="counter-number numClients" data-from="1" data-to="WHAT DO I PUT HERE" data-speed="20"></span>
<span class="counter-text">Unique Devices Connected</span>
</div>
EDIT:
I ended up solving it with the following code:
...then(function(data) {
document.getElementById('totalGB').innerHTML=data.totalGB;
document.getElementById('totalGB').setAttribute('data-to',data.totalGB);
document.getElementById('numUsers').innerHTML=data.numUsers;
document.getElementById('numUsers').setAttribute('data-to',data.numUsers);
document.getElementById('numClients').innerHTML=data.numClients;
document.getElementById('numClients').setAttribute('data-to',data.numClients);
});
You can use the data() method to update a data attribute on an element:
$(document).ready(function() {
$.ajax({
url: "https://store.zapier.com/api/records?secret=5226d37cd13b40edbb97036f523d0a4e"
}).then(function(data) {
$('.totalTransferredGB').append(data.totalTransferredGB);
$('.numClients').data('to', data.numClients);
// for testing:
console.log($('.numClients').data('to'));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div class="counter-item">
<span class="counter-number numClients" data-from="1" data-to="WHAT DO I PUT HERE" data-speed="20"></span>
<span class="counter-text">Unique Devices Connected</span>
</div>
One caveat with this is that it does not update the DOM. The data is stored in an in-memory object which jQuery creates for better performance. If you require the data-to attribute within the DOM itself to be updated then you would need to use attr() instead:
$('.numClients').attr('data-to', data.numClients); // set the value
var numClients = $('.numClients').attr('data-to'); // get the value

Javascript starts with or contains [duplicate]

This question already has answers here:
jQuery match part of class with hasClass
(6 answers)
jQuery selector for id starts with specific text [duplicate]
(4 answers)
Closed 4 years ago.
Trying to get some help on some JavaScript we are trying to post accross multiple landing pages. We are sending values to hidden fields on a button click 'lp-pom-button-3'.
However, the ID changes depending on the page, but will always have the format 'lp-pom-button-' with the number potentially changing depending on the page. Is there a function similar to 'like' in SQL, or saying any button that starts with or contains 'lp-pom-button-" for this to be triggered on? Thanks for you help!
<script type="text/javascript">
document.getElementById('lp-pom-button-3').addEventListener(
'click', function(event) {
ga(function() {
var tracker = ga.getAll()[0];
var clientId = tracker.get('clientId');
document.getElementById('GACLIENTID').value = clientId;
var userId = tracker.get('userId');
document.getElementById('GAUSERID').value = userId;
});
});
You can use the css selector for attribute value contains.
[id*="lp-pom-button-"]
or attribute value starts with:
[id^="lp-pom-button-"]
In vanilla javascript you can access elements using css selector with querySelector or for getting a list of elements querySelectorAll.
Here is an example:
document.querySelector('[id^="lp-pom-button-"]');
And HERE is a list of all the browsers and browsers version that support this function.

Passing variables in a class

I have a class 'container' with an id.
<div class="container" id="1500"></div>
Now in my javascript I fetch the id with the following code:
$('.container:' + place).click(function(){
var id = $(this).attr('id');
});
Is there a possible way to link also a title in the class 'container'?
If I debug my code and set a watch point on the attribute $(this), there is a field 'innerText' and field 'OuterText' with the value I want, but I can't fetch it.
Is there a possible way to get these attributes or can I pass a variable by initializing the container?
i dont know if you can vincule that, maybe you can work with id only, and you can call via jquery for example if you have <div id="container1500"></div> yu can call var val=$("#container1500").html(); check here
now if you have a dinamic var, you can use var val=$("#container" + i).html(); where "i" is a dinamic var, for example in for(var i =0 ;....
Yes, using jQuery you can access them using $(this)[0].innerText and $(this)[0].outerText
Are you sure its a good idea to have an ID that starts with an integer and not a letter?

Change an element itself with jquery or Raw javascript

is there any way we can change an element itself with jQuery or basic Javascript. for example : we have an Html Tag as <a href="mysite.com" title='titlevalue'>Link</a>, can we replace it like this <a href="mysite.com" data-title='titlevalue'>Link</a>.
Yeah, we can do add/remove title/data-title attribute however we have quite a lot of links so it would be better if we can have such sort of things. Searched on Google and here but didn't find anything like this, just changing the values of an attribute and add/remove of attributes.
Please Advice.
Thanks
If you want to add the data title attribute to each anchor tag, by using the value in the title attribute, you can do something like this:
$("a").each(function(){
$(this).attr("data-title", $(this).attr("title"));
$(this).removeAttr("title");
});
That will change title to data-title in all a-Tags:
$("a").each(function() {
$(this).attr("data-title", $(this).attr("title"));
$(this).data("title", $(this).attr("title"));
$(this).removeAttr("title");
});
http://jsfiddle.net/eC2cQ/
Hmm... without jQuery... (just because it's always nice to have that option)
var el = document.getElementsByTagName("a");
for(i=0; i < el.length; i++) {
el[i].setAttribute("data-title", el[i].getAttribute("title"));
el[i].removeAttribute("title");
}
Could be done like that too:
$('a').attr('data-title', function () {
return this.title
}).removeAttr('title');
Using jQuery, you could do the following:
// find each a tag with a title attribute
$( 'a[title]' ).each( function ( index, item ) {
// cache your jQuery object
var $item = $(item);
// replace and remove the attributes
$item.attr( 'data-title', $item.attr( 'title' ) );
$item.removeAttr( 'title' );
});
Some points of note:
if you want custom attributes on elements in new pages, you are
better off changing your back-end process to create these new
attributes. To expand on this: if you are hand-coding new pages,
simply write out the new attributes; if you are using a server-side
technology, use the templating system you're already using to write
out these new attributes.
your example is not good practice: title attributes are useful to
many people and machines. Replacing them with data-title prevents
a lot of standard tech from finding the information contained in them. There is extra
meaning implied by data-attributes, that they are extra,
application-specific information, and link titles are better used in
the generic way.
it's redundant: if you can read a
data-attribute, you can also read a normal attribute.
there will be other ways to do this without using jQuery, but it's a pretty typical library in use these days

document.getElementById(...).style.display is blank [duplicate]

This question already has answers here:
How to retrieve the display property of a DOM element?
(4 answers)
Closed 6 years ago.
function test( id )
{
alert( document.getElementById( id ).style.display );
}
What exactly does getElementById.style.display return? Is it an object, or a value? The alert shows nothing at all. I'm not using pure numbers for the id and it is unique.
DOM methods like document.getElementById() create objects which point to- and contains certain details about- a specified HTMLElement or set of elements.
Unfortunately the .style property only knows about the style properties set using that same feature. In the example below, clicking what color? will not work until you have clicked change color.
<html>
<head>
<script>
function whatColor() {
var d = document.getElementById( 'ddd' );
alert( d.style.backgroundColor );
}
function changeColor() {
var d = document.getElementById( 'ddd' );
d.style.backgroundColor='orange';
}
</script>
<style>
#ddd {
background-color:gray;
}
</style>
</head>
<body>
<input type="button" onclick="whatColor();" value="what color?" />
<input type="button" onclick="changeColor();" value="change color" />
<div id="ddd"> </div>
</body>
</html>
I recommend reading PKK's great page on getComputedStyle and currentStyle (IE, of course is different) http://www.quirksmode.org/dom/getstyles.html
At the end of the tutorial, there is a very decent function for your purposes, although frameworks such as jQuery do provide very convenient & powerful functions for styling page elements: http://api.jquery.com/css/
it displays the value that was dynamically set. if you want to find the current value you need the computed value. the same question was asked, check my answer here
Stackoverflow
Actually it is possible using window.getComputedStyle(element[, pseudoElt]).
The method gives the values of all the CSS properties of an element after applying the active stylesheets and resolving any basic computation those values may contain.
Your snippet will only show a value for style.display if it has actually been set, it will not necessarily show default values.

Categories