How can I use JavaScript to print non-visible code? - javascript

I am currently using the following script to echo visible text on the screen...
<h1 id="MyText"></h1>
<script>
var el = document.getElementById('MyText');
{ if (italian || french || german)
{ el.innerHTML = (
(italian && 'ciao') ||
(french && 'salut') ||
(german && 'hallo') ); }
else { el.innerHTML = 'hello';}
}
</script>
How should I edit this script, to make it work in case I want it to type a non visible word in the html?
Example:
In CSS I have:
#ciao{height:350px;}
#salut{height:10px;}
#hallo{height:3000px;}
In my code I want to define my table height basing on these conditions:
<div id="MyText">
The problem is with the above code, this will result in printing a visible text, instead of rather choosing the css id. So how am I supposed to edit the script?

It is more idiomatic to add an appropriate class to the div element. [edit] it appears as though you are looking to set the class based on the contents of the div. This is generally a difficult thing to do but here is one approach. Another would be to set a property of the div and then do a :before hack to create a pseudo element with the text of the property.
const langauges = {
"ciao":"italian",
"salut":"french",
"hallo":"german",
"hello":"english"
}
const updateClass = (el)=>{
if(langauges[el.innerHTML] != undefined){
el.className = langauges[el.innerHTML];
}
}
const onChange = (event)=>{
const el = event.target;
updateClass(el);
}
var el = document.getElementById('MyText');
el.addEventListener("input",onChange,false);
updateClass(el);
.italian{height:350px; color:blue;}
.french{height:10px; color:red;}
.german{height:3000px; color:yellow;}
.english{height:3000px; color:purple;}
<h1 id="MyText" contenteditable="true">ciao</h1>

Related

Removing elements from the DOM that were added through JS

I have tried to lookup for an answer to this but I have not been able to find an answer.
In my project, I add HTML by using JS.
let winnerHTML = 'this HTML will appear in the dom when a condition is met'
const gameCont = document.getElementById('game-container');
const decideWinner = () => {
if ( spadesPosition === 90 ||
heartsPosition === 90 ||
clubsPosition === 90 ||
diamondsPosition === 90 ) {
gameCont.insertAdjacentHTML("afterend", winnerHTML);
}
};
Now I want to remove that HTML, I've tried to set winnerHTML = ''; but clearly it's not the right logic. Since the added HTML is not part of the document, I can't select it and remove it.
Could you guys help me out here? My apologies in advance if there's already something about this but I didn't find it.
Cheers!
Add it to paragraph or span with id for later reference :
let winnerHTML = "<p id='para'>this html will appear in the dom when a condition is met<p>";
Then to remove it:
let elem=document.getElementById("para");
elem.remove();
You can also use document.createElement and store the element in a variable. Then you can use the remove function to remove it. Example
let elem = document.createElement("p");
elem.innerHTML = "Your text";
document.getElementById('game-container').appendChild(elem);
elem.remove();

Custom Javascript in google tag manager return undefined

in my footer i have a div section structured as follow:
<div id="text_icl-7" class="widget widget_text_icl">
<div class="textwidget">
<p style="text align:justify;">
<img src="image.jpg" alt="YC logo">
Some text
</p>
</div>
</div>
I want capture into a variable the text value, so i write this in gtm:
function () {
var desc = document.getElementById("text_icl-7").childNodes[1];
var p = desc.childNodes[1].childNodes[2];
return p;
}
The problem is that, debugging the page, the variable's value is undefined.
I try the script in another custom page and it works, i write the script in this way:
(function(d) {
var desc = document.getElementById("text_icl-7").childNodes[1];
var p = desc.childNodes[1].childNodes[2];
console.log(p)
})(document)
In console i get the text but not in tag manager, why?? thanks
I can't debug why you're getting undefined values, but I suspect a custom JavaScript variable is not what you need in this instance.
You can return the text contained within a DOM element by using a Google Tag Manager 'DOM Variable'. Configure your variable to use a CSS selector that selects elements that match #text_icl-7 > p. Leaving the 'attribute' field empty will return the text contained with the element by default.
i was helped by gtm forum.
The corret script is:
function() {
var el = document.querySelector('#text_icl-7');
return el && (el.textContent || el.innerText);
}
Now it works, maybe the solution of a dom variable also would works, thanks
Sorry to respond to late this but here is my solution, you need define the variable at the beginning of the script and return it at the end. Example below.
This NOT works:
function(){
document.querySelectorAll('.some-class').forEach(function(item){
var displayStyle = item.style.display;
if (displayStyle === 'block'){
return item.getAttribute('id');
}
})
}
But this works:
function(){
var result = '';
document.querySelectorAll('.some-class').forEach(function(item){
var displayStyle = item.style.display;
if (displayStyle === 'block'){
result = item.getAttribute('id');
}
})
return result;
}

Wrap an html tag after clicking a toolbar button using js or jquery

I want to do something similar to what this website and wordpress does. When a user highlights text on the screen, then clicks a button on the toolbar it will wrap an html tag around the text. In jquery I would probably use the .wrap class but how would I detect if the user highlighted something.
For example, when the user writes Hello World then clicks on the bold button it will say <b>Hello World</b>
This mainly requires (1) accessing the selectionStart and selectionEnd properties of the input/textarea element and (2) replacing the substring of the value property across that range with the same text, but wrapped in the desired start and end tags. Also, I think it makes sense to reselect the replaced text, which requires a couple of calls to select() and setSelectionRange(). Also, if there's no selection (meaning start equals end) it's probably a good idea to do nothing at all.
window.selWrapBold = function(id) { selWrap(id,'<b>','</b>'); };
window.selWrapItalic = function(id) { selWrap(id,'<i>','</i>'); };
window.selWrap = function(id,startTag,endTag) {
let elem = document.getElementById(id);
let start = elem.selectionStart;
let end = elem.selectionEnd;
let sel = elem.value.substring(start,end);
if (sel==='') return;
let replace = startTag+sel+endTag;
elem.value = elem.value.substring(0,start)+replace+elem.value.substring(end);
elem.select();
elem.setSelectionRange(start,start+replace.length);
} // end selWrap()
<input type="button" value="bold" onclick="selWrapBold('ta1');"/>
<input type="button" value="italic" onclick="selWrapItalic('ta1');"/>
<br/>
<textarea id="ta1"></textarea>
Get the text of the html element which is wrapping the text, then add as html the text embedded in the <b> tag.
See jQuery DOM Manipulation for tutorials.
I used this question to get the selected text. And this question to
get the element with selected text in it. I combined them in a single function.
function updateHighlightedText() {
var text = "";
if (window.getSelection) {
text = window.getSelection().toString();
} else if (document.selection && document.selection.type != "Control") {
text = document.selection.createRange().text;
}
var node = $(window.getSelection().anchorNode.parentNode); //Get the selected node
node.html(node.text().replace(text, "<b>"+text+"</b>")); //Update the node
}

Issue Extracting the div tag from inside another div

HI i am working in Javascript.
My code is:
var oldData = document.getElementById(id).innerHTML;
alert(oldData);
alert is shown as : text<img src="add-icon.png"><div id = "1"></div>
Here old data contains a text an image tag and a div tag. The issue is I want to just access the div tag id but i dnt know how to get it. Please help.
Thanx in advance
The thing with using vanilla JavaScript is, you've got to write all the filters yourself :)
var oldData = document.getElementById(id), firstDiv, id;
firstDiv = filterElements(node);
id = firstDiv.id;
function filterElements( node ){
var children = parent.childElements, firstDiv, node;
for (var i = 0; i < children.length; i += 1 ){
node = children[i];
if (node.tagName && node.nodeType && node.nodeType === 1 &&
node.tagName.toLowerCase() === "div"){
firstDiv = node;
break;
}
}
return firstDiv;
}
I suggest the use of jQuery. Then you can access the id of the div within its element stored as elem as
$(elem).children("div").attr("id")
If you know the parent by ID, then you can do this:
$("#"+id).children("div").attr("id")
or even this:
$("#"+id+">div").attr("id")
Of course, if you want the ID just to access an element, then you don't need to. To append a new image to the div:
$("#"+id+">div").append("<img ...>")
or
$("#"+id+">div").append($("<img>"). ...)
Also, I recommend using classes instead of childhood to identify elements:
$("#"+id+" .image-holder").append(...)
or
$("#"+id+").find(".image-holder").append(...)

Search for non-nested nodes with specific attribute set

The short long of it is I'm working on a small library in javascript that will replace <div src="somesite"></div> with the content from the specified source. This would allow coders to create dynamic pages without having to do more work server-side without the annoyance of using iframes.
What I need is an efficent way to get the top most div nodes of a branch with an src attribute. E.G:
<div src="somesite/pagelet.htm" id="div1">
<div src="somesite/fallback.htm" id="div2"></div>
</div>
<div src="somesite/pagelet2.htm" id="div3"></div>
I want to retrieve #div1 and #div3 and ignore #div2 until later. At the moment I'm using the following function, but am wondering if there is a more efficent way to do this:
function getRootElementsByAttribute(rootEle, tag, attr) {
try {
tag = tag.toLowerCase();
if (rootEle.tagName.toLowerCase() === tag && rootEle.hasAttribute(attr)) {
return [rooEle]
}
var eles = rootEle.getElementsByTagName(tag),
nodes = [], ele, isRoot, eleParent, a;
for (a=0; a<eles.length; a++) {
ele = eles[a];
if (ele.hasAttrinute(attr)) {
isRoot = true;
eleParent = ele;
while ((eleParent = eleParent.parentNode)) {
if (eleParent.tagName.toLowerCase() === 'div' && eleParent.hasAttribute(attr)) {
isRoot = false;
break;
}
}
if (isRoot == true) nodes.push(ele)
}
}
}catch(e){}
return nodes;
}
Please no answers suggesting the use of a library. It seems overkill to import a whole library when all it would be used for is this single function
You could try to use an XPath expression to get all root divs with the attribute source using something like the following XPath expression:
/div[#src]
/div selects all divs that are on the root level. For all divs in the document use //div.
[#src] specifies that you only want nodes with the 'src' attribute.
var xmlDoc = //load your document here
var xpath = "/div[#src]"
var nodes = xmlDoc.evaluate(xpath, xmlDoc, null, XPathResult.ANY_TYPE,null);

Categories