I have used a class 4 times in a page and I want to replace the content from one of them by using JavaScript
Here is the code of my html
<span class="footer">Publisher Solutions</span>
<span class="footer">Social Media 360</span>
<span class="footer">Partnerships</span>
<span class="footer">Brown Bag Presentations</span>
and I want to change like this
<span class="footer">Publisher Solutions</span>
<span class="footer">Social Media 360</span>
<span class="footer">Partnerships</span>
<span class="footer">Custom New Text From js</span>
Would something like this fits?
var elems = document.getElementsByClassName("footer");
var elem = elems[3];
elem.firstChild.href="edited_link_from_js.html";
elem.firstChild.innerHTML="My new text";
Here I manually select the 4th one, but you can change by elems.lenght - 1 if you always want last, or any selector you need.
Related
I have the following structure that cannot be changed:
<div class="activityinstance">
<a class="aalink" onclick="" href="https://...">
<img src="..../icon" class="iconlarge activityicon">
<span class="instancename">[h5p-iv] Interaktives Video
<span class="accesshide ">Interactive Content</span>
</span>
</a>
</div>
What I need to do, is to change the icon if span.instancename contains "[h5p-iv]" (plus, ideally, delete or hide that partial string from the span)
The "if" and "then" are not part of the code and the last line is unfinished, this is intended to show what I want to achieve. How do I construct an if-then in Javascript to achieve that logic?
if
$(".activityinstance .instancename:contains('[h5p-iv]')")
then
$(".activityicon") attr("src", "/static/img/icons/video.svg");
The second part is to change
<span class="instancename">[h5p-iv] Interaktives Video</span>
into
<span class="instancename">Interaktives Video</span>
that is: removing the string from "contains"
Explanation:
Moodle does not discern H5P activities, they all get the same icon. Teachers are supposed to be able to enter strings to the activity-names in order to get a different icon. So in the end there will be a list of strings linked to different icons. If that can be simplified by a switch etc., even better, but there are not that many different icons, that it would be unreasonable to repeat the code regardingly.
Additions 1: added span.accesshide because it became visible after string replacement.
Additions 2: I actually have a (kind of) working code now, but I suppose it could be done more safely and elegantly.... Any suggestions?
var elem = $(".instancename:contains('[icon-video]')");
if (elem.length) {
$(".instancename:contains('[icon-video]')").each(function() {
$(this).prev().attr("src", "/static/img/icons/video.svg");
$(".accesshide").remove();
elem.text(function(_, text) { return text.replace('[icon-video] ', '');
});
});
}
Esp. removing the .accesshide worries me, I am not sure, what it does and I would rather just remove the display and not the whole thing from the DOM. I suppose the text replace reads the whole text including the contained span.accesshide and puts the text back minus the replaced text - but also removing the span.accesshide-tag thus it looses its css that makes it invisible.
jQuery object is truthy so you would need to check its length to see if it found the element. Other thing you need to do is just do a simple string replacement
var elem = $(".activityinstance .instancename:contains('[h5p-iv]')");
if (elem.length) {
$(".activityicon").attr("src", "/static/img/icons/video.svg");
elem.text(function(_, text) { return text.replace('[h5p-iv] ', ''); });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="activityinstance">
<a class="aalink" onclick="" href="https://...">
<img src="..../icon" class="iconlarge activityicon">
<span class="instancename">[h5p-iv] Interaktives Video</span>
</a>
</div>
Now since you said it could be multiple
function replaceThis(text, imgPath) {
$(".activityinstance .instancename:contains('" + text + "')").each(function() {
const instanceName = $(this);
instanceName.find(".accesshide").hide();
instanceName.prev("img").attr("src", imgPath);
instanceName.contents().each(function(_, node) {
if (node.nodeValue && node.nodeValue.includes(text)) {
node.nodeValue = node.nodeValue.replace(text, "");
}
})
});
}
replaceThis("[h5p-iv] ", "http://placekitten.com/20/20");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="activityinstance">
<a class="aalink" onclick="" href="https://...">
<img src="..../icon" class="iconlarge activityicon">
<span class="instancename">[h5p-iv] Interaktives Video
<span class="accesshide ">Interactive Content</span>
</span>
</a>
</div>
How would I capture additional details in a div/span tag with a generic onclick event?
I.e.,
<span id=item1>Value #001<span id=clickableitem>xxx</span></span>
<span id=item2>Value #002<span id=clickableitem>xxx</span></span>
<span id=item3>Value #003<span id=clickableitem>xxx</span></span>
And then:
$(document).on('click','#clickableitem',function(e){
e.preventDefault();
// how do I get the "value #001, #002, #003" value just 'outside'
// of the span tag?
I was trying to figure it out with .parent().html(), but that didn't quite seem to work...
Thanks!
HTML:
<span id=item1>Value #001<span class="clickableitem">xxx</span></span>
<span id=item2>Value #002<span class="clickableitem">xxx</span></span>
<span id=item3>Value #003<span class="clickableitem">xxx</span></span>
JS:
$('.clickableitem').click(function() {
let text = $(this).parent().text().substring(0, $(this).parent().text().indexOf($(this).text()));
console.log(text);
});
Replacing the text is unsafe could be resulting in an empty text if the value is the same as xxxx child span....
This aproach is more effective
HTML
<span id='item1'>Value #001<span id='clickableitem1' class='spanClickable'>xxx</span></span>
<span id='item2'>Value #002<span id='clickableitem2' class='spanClickable'>xxx</span></span>
<span id='item3'>Value #003<span id='clickableitem3' class='spanClickable'>xxx</span></span>
JS
$(document).on('click','.spanClickable',function(e){
alert( $(this).parent().contents().get(0).nodeValue );
});
The id property should always be unique, instead give your span's a common className and hook up the event handler callback with it, also, in your HTML
you need to put single or double quotes around the values of properties such as id and class:
HTML:
<span id='item1'>Value #001<span id='clickableitem1' class='spanClickable'>xxx</span></span>
<span id='item2'>Value #002<span id='clickableitem2' class='spanClickable'>xxx</span></span>
<span id='item3'>Value #003<span id='clickableitem3' class='spanClickable'>xxx</span></span>
JQuery:
$(document).on('click','.spanClickable',function(e){
e.preventDefault();
//Using .text() on the parent produces the child span text as well
//Replace the child text and the word Value since all you want is
//ex. #001
const childSpanText = $(this).text();
alert($(this).parent().text().replace(childSpanText, "").replace('Value ', ''));
});
Working Fiddle
(https://jsfiddle.net/a5Lkon4j/2/)
I would like to change the text of the quickedit-label class.
<span class="quickedit" data-id="9917488">
<span class="quickedit-content">
<span class="quickedit-label">Label text</span>
<a class="rename-icon" href="#" title="Rename"></a>
</span>
</span>
I used the following code to get the text and pass it to a variable, then change the text and assign it to the element.
var labelContent = $('a.quickedit').text;
var newLabel = labelContent.subst(6,9);
$('a.quickedit').text = newLabel;
I tried using innerhtml, .data() and .value() but all returned incorrect outputs.
I know this isn't correct (and the newLabel format is just for demonstration purposes) but this should outline what I'm trying to do.
Ideally, I would like to have this within a function where the data-id of the span I want to edit is passed.
Thanks for any help on this.
You can use jquery .text( function ) method to do this work like this example.
$(".quickedit-label").text(function(index, text){
return text.substr(6, 9);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="quickedit-label">Label text</span>
I am trying to create a real-world example of get and set data attribute.
so I created a simple div that contains the data-email attribute and set a default one.
Now what I want to attain is when I click on the button it will change the default attribute to the set attribute on my JavaScript codes.
Currently I also don't know how can I show the data attribute value inside tag of my div.
here's my markup:
<div id="my-id" data-email="youremail#email.com">Sam's email is <span> "Show Email Here" </span> </div>
<button type="button" id="btn-id" onclick="click-btn()">Set Attribute Now</button>
here's my JavaScript:
var email = document.getElementById('my-id');
var emailget = email.getAttribute('data-email');
var button = document.getElementById('btn-id');
function click-btn(){
emailset = email.setAttribute('data-email', newemail#email.com);
}
here's the JSFIDDLE link: http://jsfiddle.net/jypb2jdg/6/
Any idea?
As #adeneo suggested we should not use hyphen in function name as it may be interpreted as minus sign, so remove and you may use like this:
You need to use quote in setAttribute value:
function clickBtn(){
emailset = email.setAttribute('data-email', 'newemail#email.com');
//^^ here ^^
}
You need something like this:
function clickBtn(){
emailset = email.setAttribute('data-email',
email.getAttribute('data-email') || 'newemail#email.com');
}
First thing is that the email you've written must be within quotes.
<div id="my-id" data-email="youremail#email.com">Sam's email is <span id="my-span-id"> "Show Email Here" </span> </div>
<button type="button" id="btn-id" onclick="click_btn()">Set Attribute Now</button>
The JS code:
function click_btn(){
var email = document.getElementById('my-id');
var emailContainer = document.getElementById("my-span-id");
var emailget = email.getAttribute('data-email');
emailContainer.innerText = emailget;
emailset = email.setAttribute('data-email', "newemail#email.com");
}
The code can be found in:
http://jsfiddle.net/jypb2jdg/17/
Some point I want to mention:
Include the JS before the div. Because button will not recognize click_btn() function before its declaration;
Do not use '-' symbol for function names in JS.
You could write a script without using ID for span. It will need additional structs (finding child elements, figuring out which one is what you need, set its' innertext.
You need to keep in mind that functions in javascript cannot have hyphens in their name as it is treated as a mathematical operator. Rest is just plain DOM manipulation :
<div id='my-id' data-email="youremail#email.com">Sam's email is <span id="mail"> "Show Email Here" </span>
</div>
<button type="button" id="btn-id" onclick="clickbtn()">Set Attribute Now</button>
jS:
var em;
window.onload = function(){
em = document.getElementById("my-id");
document.getElementById("mail").innerHTML = em.getAttribute("data-email");
};
function clickbtn(){
var old_mail = em.getAttribute("data-email");
em.setAttribute("data-email","newmail");
document.getElementById("mail").innerHTML = em.getAttribute("data-email");
}
Fiddle : http://jsfiddle.net/dndnqygL/4/
Note : instead of assigning a new id to the span you can also use the element.firstChild property to set the innerHTML.
I'd like to set id by for loop.This is coffee script.
for boxWidth in[0..15]
for boxLength in[0..15]
boxWidth=String(boxWidth)
boxLength=String(boxLength)
boxId =boxWidth+boxLength
$ ->
$('div').append("<span id="+boxId+"></span>")
I'm expecting span to be
<span id="00"></span>
<span id="01"></span>
<span id="02"></span>
However I've gottenn
<span id="1515"></span>
<span id="1515"></span>
<span id="1515"></span>
What is the problem?
If you are bound on using coffeescript, have you tried this:
for boxWidth in[0..15]
for boxLength in[0..15]
boxWidth=String(boxWidth)
boxLength=String(boxLength)
boxId =boxWidth+boxLength
$('div').append("<span id="+boxId+"></span>")
no need to return the div during the loop.
also you might want to check out: http://js2coffee.org