Passing a JS variable to getElementById - javascript

I am working on a small website where I want to switch tabs based on the variable passed in the URL. Here's the logic I have currently written.
var hash = window.location.href.split("#");
var count = hash.length;
if(count > 0){
var blockid = hash[1];
document.getElementById(hash[1]).css("display","block");
//document.getElementById("showthisdiv").css("display","block"); - this works
document.getElementById("broken_href").innerHTML = blockid;
}
<div class="broken_href"> </div>
hash[1] is the name of the div that I want to change the style of. If I change the hash[1] and write the name of the div in the GetElementById it works fine.
Also just to test i created a dummy div to see what value was being held by the blockid. It is passing the value correctly.
URL for testing would be something like:
http://localhost/test/#showthisdiv
What do i need to do to solve this?

This row is your problem
document.getElementById(hash[1]).css("display","block");
This .css method is a jQuery method and is not available in basic Javascript.
You could use:
document.getElementById(hash[1]).style.display = "block";
Or include jQuery and use:
$("#"+hash[1]).css("display","block");

You are trying to use css jquery method on DOM node, not on jq object
Use that instead:
$('#'+hash[1]).show();

Use
var hash = window.location.hash;
and then
document.getElementById(hash.substring(1)).style.display = "block";
If you use jQuery you can do this directly:
var hash = window.location.hash;
...
$(hash).show();
window.location.hash returns a value like this: #some-hash. This is the reason for what you need to use substring(1) when calling getElementById.

Related

getting old data-attribute value on clicking updated anchor tags [duplicate]

i have a div with data attribut like
<div class='p1' data-location='1'></div>
and i have script like
$('button').click(function(){
var loc = $('.p1').data('location');
alert('data location is'+loc);//SHOW THE DATA
var num = 10;
var count = loc;
var element = $('.p1');
var intv = setInterval(anim,1000);
function anim(){
count++;
num--;
if(count==37){count = 1;}
if(num==1){clearInterval(intv);}
$(element).animateCSS('bounceOut',{
callback: function(){
$(element).attr('data-location',count);
$(element).animateCSS('bounceIn');
}
});
}
anim();
});
with the script above the data-location attribute will be updated to 10, but if i click the button again, the data-location is still 1
The first time that you use .data() to access a data-* attribute, the value of that attribute is cached internally by jQuery, and .data() uses the cache from then on. Updating the attribute with .attr() does not update the cache, you need to use .data() to update it. That's why you need to use
$(element).data('location', count);
to update it.
$(element).attr('data-location',count);
is different than
$(element).data('location',count);
so, use the second instead.
Check Data vs Attr for details.
you are setting the attr property and not data using .attr('data-location',count). to get the attribute you need to use .attr('data-location'):
var loc = $('.p1').attr('data-location');
I know this is an old question, but I'm visiting in 2022 and really this shouldn't be done in jQuery. The caching is a bad idea, and shouldn't need to update it using their magic method.
The best method for accessing data attributes is via the JavaScript element.dataset property.
By simply calling element.dataset rather than $(element).data(), you will always get the latest data object.

JavaScript - Find ID that matches data attribute value

I have a variable that finds the data attribute of an element that is clicked on in a callback function:
var dropdown = document.getElementsByClassName('js-dropdown');
for (i = 0; i < dropdown.length; i++) {
dropdown[i].addEventListener("click", callBack (dropdown[i]));
}
function callBack (i) {
return function () {
var thisDropdown = i.getAttribute('data-dropdown');
//rest of the code here
}
}
I am basically trying to do this
$('#' + thisDropdown ).toggleClass('is-active');
...but in vanilla JS.
This works fine using jQuery however I would like a vanilla version.
So when a user clicks on an element that activates a drop down, I want it to dynamically find its relevant ID matching value within the document so it can toggle a show/hide class.
I've searched through a lot of SO questions and everyone replies with a jQuery answer which is not what I am looking for.
I've been trying to do something along the lines of
var idValue = document.getElementById(thisDropdown);
Then
var findId= idValue + thisDropdown;
findId.toggleClass('is-active');
Obviously that does not work the same way the jQuery statement works... any ideas?
Ignore the toggleClass method! Some of you may find this contradictory as I want vanilla JS.
To replace $('#' + thisDropdown ).toggleClass('is-active'); with plain js, use Element.classList. Like this:
const someElement = document.querySelector('#' + thisDropdown);
someElement.classList.toggle("is-active");
I like #kamyl's answer, but you might need backward compatibility. For that, see if you can find a polyfill.
If you have to write it yourself, use string.split(" ") to get your list of active attributes and iterate to find if it exists; add if not, remove if so...then array.join(" ") and replace the class attribute with it.

How to modify the object that passes a conditional statement

I'm kind of new in JS and jQuery, and this is my first question here, I hope I make it clear:
I have a list of <a>, and I want to apply style only to the one whose href is the same than the URL.
I tried to simplify my html to show you, something like this:
Then, this is what I started on my Script (with jQuery):
var url = window.location.pathname;
if($('a').attr('href') === url){
//and now I want to apply .css() only to the <a> that passes the condition
}
So, is frustrating I can't achieve to attack the right object, and I guess is more than simple :/, any tip?
Thanks.
The force is with you if you have CSS powers.
Simply select only that a:
$("a[href="+url+"]")
This is done using the attribute selector from CSS.
Then go ahead an do your .css() magic:
$("a[href="+url+"]").css(/*whatever you desire*/);
This will work for relative URLs like those you showed in your code.
To make it also safe for URLs like //code.google.com/whatever/abc.html you need to pass URL enclosed in single quotes:
$("a[href='"+url+"']")
Take a look at jQuery's filter().
var url = "/myWeb/004.html";
$("a").filter(function() {
return $(this).attr("href") === url;
}).css("background-color", "red");
Here is a JSFiddle.
Use filter() instead:
var url = window.location.pathname;
$('a[href]').filter(function() { return this.href === url; } ).css({
...
});

JQuery - get attr/text from HTML string in a variable

I have a HTML string that I'm passing through a function and I want to be able to perform Jquery methods on that variable from inside the function - such as .attr('href') or .text(). I'm sure there is a simple solution for this and something more elegant then temporarily appending the DOM.
HTML
<div class="here"></div>
Javascript
link = 'Google';
// This works
$('.here').html(link);
works = $('.here').text();
console.log(works);
// This doesn't
not = link.text();
console.log(not);
http://jsfiddle.net/dfgYK/
You need to create a jQuery object from link in order to use jQuery methods on it. Try:
not = $(link).text();
DEMO: http://jsfiddle.net/dfgYK/1/
Depending on what you're doing with link, it might be beneficial to do this earlier in your code so that you can just use something like:
var $link = $(link);
console.log(link.text());
You can make a jQuery object that is not part of the DOM by passing a string in:
link = $('Google');
Then, jQuery methods will work on it:
var text = link.text();
Create the link with jQuery instead:
var link = $('<a />', {
href: "http://www.google.com",
text: "Google"
});
Then you can access it's properties with link.text() like you wanted.

Adding custom data attribute for a new node in Jquery does not work

I tried to use the method data (jQuery 1.7.1) in this code:
var q = '<div class="form-error-marker"></div>';
var t = $(q).data('message', message).insertAfter(el);
and it does not work.
Note that this works:
var t = $(q).attr('data-message', message).insertAfter(el);
Why does the first variant not work?
EDIT: insertAfter works correctly and new div is added after el (which is instance of one element which I get by getElementById() function; long story short I have a library that I extend).
When I say 'it does not work' I mean that the attribute 'data-message' is not stored.
Using data like that sets an arbitrary piece of data for this node; it doesn't add a new data- attribute. Just add the attribute with the attr function, and then access it with data
var q = $('<div class="form-error-marker"></div>').attr("data-message", message);
Now access it like this:
var message = q.data("message");
Here's a fiddle
When you use jQuery.data you don't change element attributes, instead your data saved in $.cache.
So if you want to change element attributes use jQuery.attr, when you want to save some info use jQuery.data

Categories