Extract last part of ID using regex or javascript - 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();

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}}";

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/

jQuery: howto add a <br/> line break in different strings to separate sentences in 2?

I have different sentences which all have double quotes in them, like:
<h3 class="myClass">Sentence one "ends like this"</h3>
<h3 class="myClass">Sentence two"ends like that"</h3>
<h3 class="myClass">Sentence three "another ending"</h3>
All on a page. Basically all values are differents, and I'm trying to have a line break just before the double quote so it would be like
<h3 class="myClass">Sentence one <br/>"ends like this"</h3>
<h3 class="myClass">Sentence two <br/>"ends like that"</h3>
<h3 class="myClass">Sentence three <br/>"another ending"</h3>
I'm kind of confused on which jQuery function should be used to be honest, between split, text ? Any help would be appreciated , I need to understand how to do this... Many thanks!
You can match the <h3> elements, then pass a function to html(). That function will be called for each element, will be passed the current element's inner HTML markup, and must return the new markup.
From there, you can use replace() to insert a <br /> element before the first double quote character:
$("h3.myClass").html(function(index, currentHtml) {
return currentHtml.replace('"', '<br />"');
});
You can test this solution in this fiddle.
Make a function that takes a jQuery object, gets its html, and changes it
function addBR($el) {
Get the element's html
var originalhtml = $el.html();
Split the html by the quotation mark, and join them with a new <br />
var newhtml = originalhtml.split('"').join('<br />"');
Apply the new html
$el.html(newhtml);
And that's it.
Call it with
addBR(jQuery element);
Example: http://jsfiddle.net/XFC5u/
I would take a look at the Javascript split() method but in essence you have the right idea. You want to split based on the double quote(\") and that will return you an array of all the splits where a double quote occurs.
So something like this would happen:
var array = $(".myClass").text().split("\"");
//array = [Sentence one, ends like this, ];
(Not 100% sure if code is right so someone please check ><)
and then from there you can kind of recreate the text with the included . At least that's the process of how I would go about it.
Also just remember that the split method does remove the \" from the array (because it uses it as a limiter to split them) so make sure to readd them when you are recreating the text.
As for if Jquery as a specific way of doing this, I'm not sure. If anyone would like to improve my answer, feel free.
Take a look here to see this code working:
$(".myClass").each(function() {
var text = $(this).text();
var q = text.indexOf('"');
$(this).html(text.substr(0, q) + "<br />" + text.substr(q));
});
just with some basic javascript (inside a jQuery loop offcourse)
​$(".myClass").each(function() { // for each item of myClass
var text = $(this).text(); // temp store the content
var pos = text.indexOf('"'); // find the position of the "
$(this).html(text.slice(0,pos) + '</br>' + text.slice(pos)); // slice before + <br> + slice after = new content
});​​​​​​​​​​
fiddle:
http://jsfiddle.net/JaPdT/
$('.myClass').each(function(){
if($(this).text().indexOf('"') >=0 ){
$(this).text( $(this).text().replace('"', '<br/>"') )
}
})

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

Javascript: read number of any value

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

Categories