Overwrite a class via JavaScript - javascript

I want to overwrite some text defined by class=cc-product-infolink and it is defined by the CMS, so i have to change the text in this class via JS. It is my first time to use it, so i have wrote a little script, but it doesn't work. Why?
I would like to change the text "inkl. MwSt, zzgl. Versandkosten " in "inkl. MwSt, Versandkosten gemäß Angaben". And the JS-Code must be work in the head, because there is no possibility to put it into the body.
Here is my HTML Code:
<div class="cc-product-infolink">
<a class="cc-no-clickable-arrow" href="/j/shop/info/m/me6f40c3b0bd58b35" rel="nofollow">inkl. MwSt, zzgl. Versandkosten</a>
</div>
My JS-Code
<script type="text/javascript">
//<![CDATA[
var versand = document.getElementsByClassName('cc-product-infolink')[0];
versand.getElementsByTagName('a')[0].textContent += ' gemäß Angaben';
//]]>
</script>
and it should work here: http://www.wonnemond.de/taschen/karl/#cc-m-product-8254989095
Maybe somebody can help me.

var versand = document.getElementsByClassName('cc-product-infolink')[0];
versand.getElementsByTagName('a')[0].textContent += ' gemäß Angaben';
Some notes:
id and class are not the same. As the name implies, getElementById retrieves elements by their id attribute. Your element only has class, so getElementsByClassName is what you need. I guess you cannot change the HTML.
textContent is used to set/get
the text content of a DOM element. Old IEs (IE8 and older) use
innerText instead.
firstChild does not work because the link is not the first child of that div. There is a text node containing a newline and some indentation before the link. Using getElementsByTagName you can solve this problem though.
And a jsFiddle Demo.

Related

How to set an "id" to a tag using the execCommand in Javascript?

I am trying to make up a basic text editor, and I used execCommand a lot for this.
However, I want to create a heading in such a way, so that whenever user will click on the heading button(in text editor), the execCommand will make up a new heading and should add id to the newly created heading, so that, later I can create interlinks in document with just a single click.
Let say my input in for heading text editor is:
Create a heading with id
I've tried this to create a heading with id:
document.execCommand('formatBlock', false, header).id = userSelection;
HTML output for this:
<h3>Create a heading with id</h3>
As you can see, the id is not added to the HTML output, so how can I add an id to it?
I've also tried this link but didn't get much:
How to add class or id or CSS style in execCommand formatBlock 'p' tag?
Please help :)
EDIT :
Well, I got a hack to do this:
We can add the id to the newly created tag by using the Query selector so that whenever I will create a new tag using execCommand, I will find that tag by selecting the main div(in which editing is going on), and after finding that header tag, I can simply add the id to it.
Like I used this to create a header tag in div(contenteditable="true"):
document.execCommand('formatBlock', false, header);
And to add 'id' to this newly created tag, use this:
let elemMain = $("#editor " + header);
// this will find the div with id="editor" and then find the header tag inside it.
elemMain[elemMain.length - 1].id = userSelection;
//this will add an id to the last header tag inside of div.
Well, this is just a hack to get work done, but if anyone finds out a direct way to add 'id' to tag using execCommand then most welcome :)
Adding id attribute to the <body> tag here using execCommand.
Using javascript :
var idValue = "body-element";
document.execCommand(document.body.setAttribute("id", idValue));
Using jquery :
var idValue = "body-element";
document.execCommand($('body').attr('id', idValue));
Working snippet for newly created element:
var para = document.createElement("p");
var node = document.createTextNode("This is newly created paragraph ( inspect this element and see the id.)");
para.appendChild(node);
var element = document.getElementById("div1");
element.appendChild(para);
var idValue = "new_id";
document.execCommand(para.setAttribute("id", idValue));
<html>
<body>
<div id="div1">
<p id="p1">This is an old paragraph.</p>
</div>
</body>
</html>
Had the same requirement to use document.execCommand to manipulate a contenteditable element, and eventually resorted to the innerHTML option of execCommand. For example...
document.execCommand("insertHTML", false, "<div id='myId'>Hello World!</div>")
...adds the specified HTML at the insertion point, leaving the HTML element addressable by myId. The drawback to this technique is that one has to construct the HTML string. An alternative is to employ the createElement function, and then reference the outerHTML of the element node when calling execCommand...
let elemNode = document.createElement('div')
elemNode.id = 'myId'
elemNode.innerText = 'Hello World!'
document.execCommand('insertHTML', false, elemNode.outerHTML)
Note that I only tested this on Chrome.
Hope this helps anyone else finding this nook of the internet.

javascript replace text after the page has loaded

I want to remove/hide a piece of text that loads on my page.
The element doesn't have an id to relate to so I want to use a text-specific method.
Let's say the text is:"remove this line of text".
The html looks like this:
<div class="aClassName">
<p>
<strong>remove this line of text</strong>
... the rest of the content.
</p>
I have tried the following:
jQuery(document).ready(function($){
document.body.innerHTML = document.body.innerHTML.replace('remove this line of text', '');
});
Didn't work. So I tried this:
jQuery(document).ready(function($){
$("body").children().each(function () {
$(this).html( $(this).html().replace(/remove this line of text/g,"") );
});
});
Didn't work. The idea is that after the page is loaded it removes the line.It doesn't produces any errors as well. Not even in the firebug.
Anyone?
Target Elements Based On Their Content
You could accomplish this using the :contains() pseudoselector in jQuery that would allow you to target certain elements based on their contents :
$(function(){
// This will remove any strong elements that contain "remove this line of text"
$('strong:contains("remove this line of text")').remove();
});
You can see a working example of this here.
Broader Approach (Just Targets Elements Based On Selectors)
If you wanted a more simply target it by a more general selector (i.e. any <strong> tags that appear beneath a class called aClassName :
$('.aClassName strong').remove();
You can see an example of this approach here.
I guess you can use find() and text(), i.e.:
$('.aClassName').find('strong').text("123");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="aClassName">
<p>
<strong>remove this line of text</strong>
... the rest of the content.
</p>
Or simply:
$('strong:contains("remove this line of text")').text("New text");
Update:
After analyzing the link supplied on the comments, you can use the following:
$('.payment_method_mollie_wc_gateway_ideal').find('strong').text("");

How to insert text and html within a tag where the text appears first and html appears second

I have been looking on the internet, but I failed to find the correct solution.
What I have here erases the text content with the html, and I need both there.
On the markup I need something like this:
<h1 class="stock-count">54<span class="stock-count-info">In Stock</span></h1>
But I keep getting something this (without 54):
<h1 class="stock-count"><span class="stock-count-info">In Stock</span></h1>
This is the jQuery code I have tried:
$(".stock-count").text(count);
$(".stock-count").html("<span class='stock-count-info'></span>");
$(".stock-count-info").text("In Stock");
Has anyone got any suggestions?
PS. The span tag HAS to be within the h1 tag.
Try this : You can add count and stock-count-info span directly to html of stock-count span in a single call.
$(".stock-count").html(count+"<span class='stock-count-info'>In Stock</span>");
You can use .append():
$(".stock-count").append("<span class='stock-count-info'>In Stock</span>");
use prepend to insert the element before
$(".stock-count").html("<span class='stock-count-info'></span>").prepend(count);

Insert HTML as a String, without JQuery

I'm looking for a method to insert a string, which contains HTML data, into a div element.
The string is loaded via XHR, and there is no way of knowing what elements and such are in it.
I've searched around for a bit, and found some things that might help, but wouldn't completely work for me. What I need is something similar to the update() function from the Prototype framework:
http://prototypejs.org/api/element/update
The platform I'm writing for does not allow frameworks to be used, or JQuery. I'm stuck with Javascript. Anyone have any ideas?
I can't use innerHTML, as it does not apply any updates or functions or basically anything that's supposed to occur on load
I have some onload events that need to occur, and as best I know, using innerHTML does not execute onload events. Am I incorrect?
EDIT 2 years later:
For anyone else reading, I had some serious misconceptions about the onload event. I expected that it was a valid event for any element, while it is only valid for the <body/> element. .innerHTML is the proper method to do what I was looking for, and any extra functionality for the elements added, needs to be done manually some other way.
HTMLElement innerHTML Property
The innerHTML property sets or returns the inner HTML of an element.
HTMLElementObject.innerHTML=text
Example: http://jsfiddle.net/xs4Yq/
You can do it in two ways:
var insertText = document.createTextNode(theText);
document.getElementById("#myid").appendChild(insertText);
or
object.innerHTML=text
I'm looking for a method to insert a string, which contains HTML data, into a div element.
What you want to use is the innerHTML property.
Example of use:
<script type="text/javascript">
function changeText(){
document.getElementById('boldStuff').innerHTML = '<p>Universe</p>';
}
</script>
<p>Hello <b id='boldStuff'>World</b> </p>
<input type='button' onclick='changeText()' value='Change Text'/>
do you mean like this? : http://jsfiddle.net/FgwWk/1 or do you have things in the div already before adding more?
Plain JS.
Just use: element.insertAdjacentHTML(position, text);
position = "beforebegin" | "afterbegin" | "beforeend" | "afterend"
var text = '<a class="btn btn-blue btn-floating waves-effect">\n' +
'<i class="fas fa-user"><span class="badge badge-danger"></span></i>\n' +
'</a>';
var inputPlace = document.getElementById("input-pace");
inputPlace.insertAdjacentHTML("beforeend", text);

extracting text from html file

I'm trying to get nodes containing text from html file using Javascript and jQuery.
if I have a node like
`
<div>txt0
<span>txt1</span>
txt2
</div>
How can I select elements that meets this criteria??
Meaning, I need to retrieve thedivand thespan` , and it would be even better to know location of the text.
I'm trying to get the text to replace it with images in a later function.
I tried this
`
$('*').each(function(indx, elm){
var txt = $(elm).text();
// my code to replace text with images here
});
`
but it does not get the required results.. it does all the parsing in the first element, and changes the html totally.
I don't know exactly what you're trying to solve, but perhaps you can be a bit more specific with your selector?
$("div span").text(); // returns 'txt1'
$("div").text(); // returns 'txt0txt1txt2'
By adding ids and/or classes to your html, you can be very specific:
<div class="name">Aidan <span class="middlename">Geoffrey</span> Fraser</div>
...
// returns all spans with class
// "middlename" inside divs with class "name"
$("div.name span.middlename").text();
// returns the first span with class
// "middlename" inside the fourth div
// with class "name"
$("div.name[3] span.middlename[0]").text();
JQuery has pretty good documentation of these selectors.
If this doesn't help, consider explaining the problem you're trying to solve.
Your markup structure is a bit uneasy. Consider changing to something like this
<div>
<span>txt0</span>
<span>txt1</span>
<span>txt2</span>
</div>
Then using jQuery
$("div span").each(function(k,v) {
$(this).html("<img src=\""+v+".jpg\" />"); //replace with the image
});

Categories

Resources