Javascript: read number of any value - javascript

I'm trying to apply a tooltip to a foreach loop, but I need the javascript to read the attribute "mystickytooltip" with a number at the end.
<div id="mystickytooltip{$smarty.foreach.cart.iteration}" class="stickytooltip">
Will output
<div id="mystickytooltip1" class="stickytooltip">
<div id="mystickytooltip2" class="stickytooltip">
<div id="mystickytooltip3" class="stickytooltip">
And I need the javascript to read "mystickytooltip(ANYVALUE)" is this possible? My JS knowledge sucks.
//stickytooltip.init("targetElementSelector", "tooltipcontainer")
stickytooltip.init("*[data-tooltip]", "mystickytooltip")
Thanks.

In your previous (now deleted) question, it looked like you were using jQuery. If that's the case, you should just be able to use a class selector:
var myToolTips = $("div.mystickytooltip");
Or you could use the Attribute Starts With selector:
var myToolTips = $("div[id^='mystickytooltip']");
The only possible drawback I could forsee with the attr-starts-with selector is if you have any other div elements whose id begins with "mystickytooltip" (ie, "mystickytooltipcontainer"). In that case you could combine the class and attr-starts-with selectors:
var myToolTips = $("div.mystickytooltip[id^='mystickytooltip']");

You can try this :
var i=1; // starting index
while(document.getElementById('mystickytooltip'+i)) {
stickytooltip.init("*[data-tooltip]", "mystickytooltip"+(i++));
}
In english : as long as you can find an element with id 'mysticktooltip'+i (+ is string concatenation in js), call stickytooltip.init with this id as second parameter (and increment i).

Related

How can I set attribute which ends with dollar sign using Javascript?

I'm trying to create a pre-processor that converts some custom markup in a file into attribute names which works with Polymer's data binding $= annotation, however I've come across a stumbling block.
I cannot set attributes using Javascript that contain a dollar sign.
I'm trying to convert
<p stuff="align bottom#md top#lg; offset 2gu#md; "></p>
to
<p align-bottom$="{{globals.abovemd}}" align-top$="{{globals.abovelg}}" offset-2gu$="{{globals.abovemd}}">
I have tried:
.setAttribute("align-bottom$", "{{globals.abovemd}}");
But it won't work because the attribute name cannot contain a dollar sign.
Can any one think of a way I can get around this?
This might do the trick(setting invalid attribute names), although obviously not valid in all cases:
function setDollar(el,name,val){
var attrs = [];
var tagName = el.tagName;
for (var i = 0; i < el.attributes.length; i++) {
var attrib = el.attributes[i];
if (attrib.specified) attrs.push(attrib.name+'="'+attrib.value+'"')
}
el.outerHTML = '<'+tagName+ ' '+name+'$="'+val+'"'+attrs.join(' ')+'>'+ el.innerHTML+'</'+el.tagName+'>';
attrs.forEach((attr)=>el.setAttribute(attr.name, attr.value))
}
setDollar(document.querySelector('#wow'),'foo','bar')
<div id="wow"><p>something</p></div>
Still, needs checking for closing tag etc.
Just exclude the $ anytime you are dealing with that property. The $ is just reflecting the property to the attribute onto that DOM element.
.setAttribute("align-bottom", globals.abovemd);
Pretty sure this gonna work
(you need put align-bottom$="" into your html first, this is just to update the value):
.attributes['align-bottom$'].value = "{{globals.abovemd}}";

Extract last part of ID using regex or javascript

I have a component with an ID that is composed of a first static part and a second dynamic value, like this:
<div id="smallPlacardone">
Where: smallPlacard is static and one is passed using a variable.
Later in my code I want to use the dynamic part of the ID, namely one, but not the first static part smallPlacard, like this:
var clicked = $(this).parent().attr("id");
$("#right"+clicked+"").show();
What's the best way of doing it?
If "smallPlacard" is static, then you can just remove it using the replace method:
var clicked = $(this).parent().attr("id").replace(/smallPlacard/, '');
$("#right" + clicked).show();
I recommend working with delimiter chars and split(). It's easier to read and avoids the regex entirely:
<div id="smallPlacard_one">
and
var clicked = $(this).parent().attr("id").split("_")[1];
$("#right_" + clicked).show();
Alternatively something like this, which is more flexible because it does not rely on hidden conventions:
<div id="smallPlacard_one" data-show="#right_one">
and
var selector = $(this).data("show")
$(selector).show();

Javascript - How to get attribute value from a tag, inside a specific div class?

Snippet of HTML code I need to retrieve values from:
<div class="elgg-foot">
<input type="hidden" value="41" name="guid">
<input class="elgg-button elgg-button-submit" type="submit" value="Save">
</div>
I need to get the value 41, which is simple enough with:
var x = document.getElementsByTagName("input")[0];
var y = x.attributes[1].value;
However I need to make sure I'm actually retrieving values from inside "elgg-foot", because there are multiple div classes in the HTML code.
I can get the class like this:
var a = document.getElementsByClassName("elgg-foot")[0];
And then I tried to combine it in various ways with var x, but I don't really know the syntax/logic to do it.
For example:
var full = a.getElementsByTagName("input")[0];
So: Retrieve value 41 from inside unique class elg-foot.
I spent hours googling for this, but couldn't find a solution (partly because I don't know exactly what to search for)
Edit: Thanks for the answers everyone, they all seem to work. I almost had it working myself, just forgot a [0] somewhere in my original code. Appreciate the JQuery as well, never used it before :-)
The easiest way is to use jQuery and use CSS selectors:
$(".elgg-foot") will indeed always get you an element with class "elgg-foot", but if you go one step further, you can use descendent selectors:
$(".elgg-foot input[name='guid']").val()
That ensures that you only get the input named guid that is a child of the element labelled with class elgg-foot.
The equivalent in modern browsers is the native querySelectorAll method:
document.querySelectorAll(".elgg-foot input[name='guid']")
or you can do what you have yourself:
var x = document.getElementsByClassName("elgg-foot")
var y = x.getElementsByTagName("input")[0];
Assuming you know it is always the first input within the div
You can combine it like this:
var a = document.getElementsByClassName("elgg-foot")[0];
var b = a.getElementsByTagName("input")[0];
var attribute = b.attributes[1].value;
console.log(attribute); // print 41
Think of the DOM as the tree that it is. You can get elements from elements in the same way you get from the root (the document).
You can use querySelector like
var x = document.querySelector(".elgg-foot input");
var y = x.value;
query the dom by selector https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector
var fourty1 = document.querySelector('.elgg-foot input[name=guid]').value;
querySelector will return the first match from the selector. This selector will find the element with class elgg-foot and then look at the input element inside of that for one named guid and then take the value of the selected element.
I think the simplest way would be using JQuery. But using only javascript,
the simplest way would be:
var div = document.getElementsByClassName("elgg-foot")[0];
var input = div.getElementsByTagName("input")[0];
alert(input.value)
Take a look at this JSFiddle here: http://jsfiddle.net/2oa5evro/

Extracting values from Array with Javascript

I am having issues with getting exactly values with Javascript.
Following is working version of when we have class on single item.
http://jsfiddle.net/rtnNd/
Actually when code block has more items with same class (see this: http://jsfiddle.net/rtnNd/3), it picks up only the first item which use the class name.
My issue is that I would like to pick up only the last item which use the class name. So I used following code:
var item = $('.itemAnchor')[6];
var href = $($('.hidden_elem')[1].innerHTML.replace('<!--', '').replace('-->', '')).find(item).attr('href');
But it doesn't work though. I don't really know why.
The code that may contains items are using same class, class may be use in 2 items, 3 items, or 6th times. That's why, I want to pick up only the last item to extract.
Can you explain, thank you all for reading my question.
"My issue is that I would like to pick up only the last item which use the class name."
OK, so in a general sense you would use the .last() method:
var lastItem = $('.itemAnchor').last();
Except that there are no elements in the DOM with that class because (in your fiddles) they're all commented out. This is also the reason why the code you showed in your question didn't work. The first line:
var item = $('.itemAnchor')[6];
...sets the item variable to undefined. The selector '.itemAnchor' returns no elements, so $('.itemAnchor') is an empty jQuery object and it has no element at index 6.
You need to use the '.itemAnchor' selector on the html that you get after removing the opening and closing comments with your .replace() statements, so:
var href = $($('.hidden_elem')[0].innerHTML.replace('<!--','').replace('-->',''))
.find('.itemAnchor').last().attr('href');
Demo: http://jsfiddle.net/rtnNd/4/
EDIT in response to comment:
"How can we pick up the itemElement before that last one."
If you know you always want the second-last item use .slice(-2,-1) instead of .last(), as shown here: http://jsfiddle.net/rtnNd/5/
Or if you know you want whichever one has an href that contains a parameter h= then you can use a selector like '.itemAnchor[href*="h="]' with .find(), in which case you don't need .last() or .slice():
var href = $($('.hidden_elem')[0].innerHTML.replace('<!--','').replace('-->',''))
.find('.itemAnchor[href*="h="]').attr('href');
Demo: http://jsfiddle.net/rtnNd/6/
Note though that this last method using the attribute-contains selector is picking up elements where the href has the text "h=" anywhere, so it works for your case but would also pick up hh=something or math=easy or whatever. You could avoid this and test for just h= as follows:
var href = $($('.hidden_elem')[0].innerHTML.replace('<!--','').replace('-->',''))
.find('.itemAnchor')
.filter(function() {
return /(\?|&)h=/.test(this.href);
}).attr('href');
Demo: http://jsfiddle.net/rtnNd/7/

How can I replace a class with another using jQuery?

What jquery can I use to change the class that's used in the following from indent_1 to indent_2 or indent_4 to indent_2? I know about remove class but how can I do that when the classes are names that vary?
<div class="rep_td0 indent_1" id="title_1">Menu two</div>
or
<div class="rep_td0 indent_4" id="title_1">Menu two</div>
Since you haven't been very specific about exactly what class you want to change to another and you've said you want to deal with the case where you don't know exactly what the class is, here are some ideas:
You can find all objects that have a class that starts with "indent_" with this selector:
$('[className^="indent_"]')
If you wanted to examine the class on each one of those objects, you could iterate over that jQuery object with .each() and decide what to do with each object or you could use removeClass() with a custom function and examine the class name and decide what to do with it.
If you just wanted to change all indent class names to indent_2, then you could use this:
$('[className^="indent_"]').removeClass("indent_1 indent_3 indent_4").addClass("indent_2");
or, using a custom function that can examine the class name with a regex:
$('[className^="indent_"]').removeClass(function(index, name) {
var match = name.match(/\bindent_\d+\b/);
if (match) {
return(match[0]);
} else {
return("");
}
}).addClass("indent_2");
Or, if all you want to do is find the object with id="title_1" and fix it's classname, you can do so like this:
var o = document.getElementById("title_1");
o.className = o.className.replace(/\bindent_\d+\b/, "indent_2");
You can see this last one work here: http://jsfiddle.net/jfriend00/tF8Lw/
If you're trying to make this into a function that could take different numbers, you could use this:
function changeIndentClass(id, indentNum) {
var item = document.getElementById(id);
item.className = item.className(/\bindent_\d+\b/, "indent_" + indentNum);
}
try this code,
$("#title_1").removeClass("indent_1").addClass("indent_2");
if you not sure which is available, try this
$("#title_1").removeClass("indent_1").removeClass("indent_4").addClass("indent_2");
Updated:
$("#title_1").removeClass(function() {
var match = $(this).attr('class').match(/\bindent_\d+\b/);
if (match) {
return (match[0]);
} else {
return ("");
}
}).addClass("indent_2");
Try below :
$('#title_1').removeClass('indent_1').addClass('indent_2');
Here, the indent_1 classes will be replaced with indent_2.
Maybe this?: Remove all classes that begin with a certain string
That answers how to replace a classname on a jQuery element that has a specific prefix, such as 'indent_'.
While that answer doesn't specifically address replacement, you can achieve that by altering one of their answers slightly:
$("selector").className = $("selector").className.replace(/\bindent.*?\b/g, 'indent_2');
Or similar...
First things first...If you have multiple elements on your page with the exact same ID you're going to have problems selecting them by ID. Some browsers won't work at all while others may return just the first element that matches.
So you'll have to clean up the ID thing first.
You can use the starts with selector to find all the classes that match your class name patter and then decide if you want to switch them or not:
$('[class^="indent_"]').each(function() {
var me = $(this);
if(me.hasClass("indent_1").removeClass("indent_1").addClass("indent_2");
});

Categories