On a project I'm working on, a HTML file is defining a Javascript template used on selection buttons. All buttons have a "Change..." label that I want to localize (set dynamically). In other cases I'm searching for the element ID and setting the InnerHTML accordingly. But in this case, the ID of the buttons are defined dynamically. Is it possible to have a text element inside the button element, search for this element, and set its InnerHTML value?
<script id="optionSelectionTemplate" type="text/x-handlebars-template">
<div class="sub-section option-selection">
{{#if name}}<h4>{{name}}</h4>{{/if}}
<div class="current"></div><button class="button" id="{{id}}" data-action-id="{{id}}">Change...</button>
</div>
</script>
I've been searching this for a while now. But given that my forte is not web development, I'm not really sure what to search for...
You may be able to get the button element(s) by its class instead; for example:
var x = document.getElementsByClassName("button");
As you suggested, you can improve your selection's precision by first getting the 'optionSelectionTemplate' element(s) like so:
var x = document.getElementById("optionSelectionTemplate").getElementsByClassName("button");
Or if you prefer:
var x = document.getElementById("optionSelectionTemplate").getElementsByTagName("button");
Here are some links for more on these method:
https://www.w3schools.com/jsref/met_document_getelementsbyclassname.asp
https://www.w3schools.com/jsref/met_document_getelementsbytagname.asp
Depending on how dynamic your localization should become, you could also specify the text inside a (locale-dependent) CSS as in https://jsfiddle.net/1gws5kat/ :
[HTML]
<button class="button btn_change" id="{{id}}" data-action-id="{{id}}"></button>
[CSS]
.btn_change:before { content: "Change..."; }
In particular when dealing with a large number of identically-named elements (i.e. many "Change" buttons), this might be pretty handy.
You find those btns by this command:
var btnlist= $(':button')
This Camano get you all button in your html file, then loop ton in and apply your changing.
Before call this command, jquery must be install.
Related
I'm looping through all elements of a certain class on a page and editing the text of an tag in that class with a certain id. I'm referencing the element with $(this).find('#time') and trying to change the text of that object using $(this).find('#time').text("test"), but the the text of the element isn't changing and I can't figure out why.
EDIT:
$('.box').each(function(i, obj){} This is what the loop is, the odd thing is that when i simply reference the text with $(this).find('#time').text() i receive the correct output. But the text won't change when using .text().
Here is the code im using to change the object text:
var time = response.substring(7, 15);
var user = response.substring(16, response.length);
$(this).find('#time').text(time);
$(this).find('#name').text(response.substring(user));
Game Page
<div class="box">
<h1>${{ game_object.amount }}</h1>
<h2 id="time">{{ game_object.start_time}}</h2>
<p id="name">{{ game_object.current_top_user }}</p>
CLICK NOW
</div>
Try to use .html
$(this).find('#time').html("test")
or maybe this can help you:
$('body').find('#time').text('test');
Because the ID of an element must to be unique
I have a couple of dashboard pages rendered and view elements coded for one page that looks like:
<td class="secondaryTabSelected" title="Pace">
<span tabindex="0">Pace</span>
</td>
I want to extract the name called "Pace" from above using Javascript, after the user has clicked on a specific tab title called "Pace". How can I achieve this?
I have tried:
var a = document.getElementsByClassName('secondaryTabSelected')[0];
var b = a.getElementsByClassName("child")[0].innerHTML;
alert(b); //assume b is my extracted text
document.querySelectorAll() is often a better function to use when trying to query the DOM for elements. It essentially allows you to use CSS selector syntax to perform more complicated queries (much like jQuery) and has support down to IE8.
In your case:
var spanElement = document.querySelectorAll(".secondaryTabSelected span")[0];
alert(spanElement.innerText);
Should perform what you are trying to achieve.
There are two issues in your code:
td need to be nested in in node, otherwise the browser will remove the tag.
you haven't put child as a class in html
You can either remove the first line and add class direclty in your target node or use childNodes instead
var a = document.getElementsByClassName('secondaryTabSelected')[0];
console.log(a);
var b = a.childNodes[1].innerHTML
console.log(b);
<div class="secondaryTabSelected" title="Pace">
<span tabindex="0">Pace</span>
</div>
Is possible change color of background my div using JavaScript without using ID? And how?
Html code is:
<div class="post" onmouseover="test(this)">
JS code is:
function test(item){
alert("Hi :-)");
}
Have you tried
function test(item){
item.style.backgroundColor = "red";
}
Since item is the actual div you're triggering this event on you won't need an ID to style the element.
A really easy (inline) solution would be the one below.
<div class="post" onmouseover="javascript:style.backgroundColor = 'red';">
Content blabla
</div>
I would personally rather do all of this inside a JS file but hey this works too.
You can loop through the DOM with JavaScript, but you'll have a better time of it if you're using JQuery. You'll want to invest some time learning about selectors:
http://api.jquery.com/category/selectors/
http://www.w3schools.com/jquery/jquery_ref_selectors.asp.
You'll be looking for something like:
function test(){
var element = $('div');
}
As people have shared in the comments, without a unique identifier, you'll have a rough time, especially as new elements are added to the page.
I'm trying to add a span to a label for which I don't have access to the HTML as it's output from RSForms Pro. I would like to add a tooltip span to individual labels so when the person rolls their mouse over, they get some information.
Here is what the code looks like:
<p class="rsformVerticalClear"><input name="form[Services_DM][]" type="checkbox" value="Death Records Retrieval/Search" id="Services_DM0"><label for="Services_DM0">Death Records Retrieval/Search</label></p>
The next option has the class Services_DM1 and so forth.
How do I go about adding a span to "Death Records Retrieval/Search" without having access to the actual code? Is there a way to inject it?
How are you inserting the code into your page? Anything embedded (such as an Iframe) will be barred from being manipulated from (or, IIRC, accessed by) your javascript due to XSS concerns.
Assuming your html and the loaded html are rendered into the same document, you'd want to use the HTML DOM functions to manipulate the html post load. This function should do what you want:
function addToolTip(elementid, content, classname) {
var theelement=document.getElementById(elementid);
var thetooltip=document.createElement('span');
var thetext = document.createTextNode(content);
thetooltip.appendChild(thetext);
thetooltip.setAttribute('class',classname);
theelement.appendChild(thetooltip);
}
To generate a tooltip, just call addToolTip with your label's element, whatever content text you'd like to see within the tooltip, and a css class (I figured you may want this for styling).
You can target all the labels with class starting from "Services_DM" and append a span to them:
try this jQuery sample snippet.
var $span = $('<span>My span contents here </span>');
$('label[class^="Services_DM"]').each(function(index,item){
$(this).append($span);
});
The above code is not tested, for reference purpose only!
I've been building a list of links, all of which should change the content of a div to another specific content (about 4 lines of stuff: name, website, contact etc.) upon a click.
I found this code:
<script type="text/javascript">
function ReplaceContentInContainer(id,content) {
var container = document.getElementById(id);
container.innerHTML = content;
}
</script>
and used it in such a way:
<li class="pl11">
superlink')">Pomorskie</a>
</li>
And it doesn't work as I expected.
It changes hyperlinks text from 'Pomorskie' to 'superlink'.
The plain text works just fine but I need links.
here's the http://xn--pytyfundamentowe-jyc.pl/projektanci/kontakty-p/ (only two of them show anything)
But after trying all of your recomendations, I think I'd jump to different divs with #links, cause nothing worked with this :/
Thanks a lot for trying, and cheers :)
Just as a completely sideways look at this, I'd suggest avoiding the nesting weirdness / complexity, and reducing the problem down.
Setup the content in a hidden (ie. <div id="replacements">...</div>) Grab the innerHTML from the node you want, and be done with it.
Much easier to get replacement content from non-devs that way too, kinda works great if you're in a team.
// Probably better in a separate helpers.js file.
function replaceContentInContainer(target, source) {
document.getElementById(target).innerHTML = document.getElementById(source).innerHTML;
}
Control it with: (lose that href=javascript: and use onClick, better as an event handler, but for brevity I'll inline it as an onClick attribute here, and use a button.)
<button onClick="replaceContentInContainer('target', 'replace_target')">Replace it</button>
We have our target somewhere in the document.
<div id="target">My content will be replaced</div>
Then the replacement content sits hidden inside a replacements div.
<div id="replacements" style="display:none">
<span id="replace_target">superlink</span>
</div>
Here it is in JSBin
Improve the dynamic nature of this by using Handlebars or another nice JS templating library, but that's an exercise for the OP.
edit: Note, you should also name functions with a leading lowercase letter, and reserve the leading uppercase style for Class names e.g. var mySweetInstance = new MySpecialObject();
The quotes are mismatched! So when you click you are getting a JavaScript error.
The browser sees this string:
href="javascript:ReplaceContentInContainer('wojewodztwo', 'superlink')">Pomorskie<
as:
href="javascript:ReplaceContentInContainer('wojewodztwo', '<a href="
Chnage the " inside to #quot;
<li class="pl11">
Pomorskie
</li>
Example fiddle.
Also note, using the href tag for JavaScript is a BAD practice.
You've got a problem with nested quotes. Take a look in your DOM inspector to see what the HTML parser built from it! (in this demo, for example)
You either need to HTML-escape the quotes inside the attribute as " or ", or convert them to apostrophes and escape them inside the JS string with backslashes:
<a href="j[…]r('wojewodztwo', '<a href="http://address.com">superlink</a>')">…
<a href="j[…]r('wojewodztwo', '<a href=\'http://address.com\'>superlink</a>')">…
See working demos here and here.
Better, you should use a onclick attribute instead of a javascript-pseudo-url:
<a onclick="ReplaceContentInContainer('wojewodztwo', …)">Pomorskie</a>
or even a javascript-registered event handler:
<li class="pl11">
<a id="superlink">Pomorskie</a>
</li>
<script type="text/javascript">
function replaceContentInContainer(id,content) {
var container = document.getElementById(id);
container.innerHTML = content;
}
document.getElementBId("superlink").onclick = function(event) {
replaceContentInContainer('wojewodztwo', 'superlink');
event.prevenDefault();
};
</script>
(demo)