div / bold contains text give class [duplicate] - javascript

This question already has answers here:
Find a string of text in an element and wrap some span tags round it
(6 answers)
Closed 6 years ago.
I've got a loot box div in which (sometimes) the name colorful comes in.
for example:
<div id="columns">
<div id="loot">
<b>
"Loot: Colorful blade "
<br>
" slot: weapon "
<br>
" value: 7"
</b>
...more and more and more
Now if the text in the loot div contains colorful I want to add a class to the text colorful . So I thought that if the text colorful is in it, it puts a <span> around the word colorful and asign a class to it. But I cant figure out how to do this.
I tried this (jsfiddle)

Your code targets the #loot element when trying to add the rainbow class, but does it target the desired div when looking for the text in the first place? (I dont think it does, but dunno since I dont jQuery)
Here's some code to do it sans jQuery:
var tgtElem = document.getElementById('loot');
var value = tgtElem.innerHTML;
value = value.replace('Colorful', '<span class="highlight">Colorful</span>');
tgtElem.innerHTML = value;
It relies upon a css rule, .highlight - set its styles as you wish.
Here's a fully worked example:
<!DOCTYPE html>
<html>
<head>
<script>
"use strict";
function byId(id){return document.getElementById(id);}
//////////////////////////////////////////////////////////////////////////////
window.addEventListener('load', onDocLoaded, false);
function onDocLoaded()
{
var tgtElem = byId('loot');
var value = tgtElem.innerHTML;
value = value.replace('Colorful', '<span class="highlight">Colorful</span>');
tgtElem.innerHTML = value;
}
</script>
<style>
.highlight
{
background-color: yellow;
font-weight: bold;
}
</style>
</head>
<body>
<div id="columns">
<div id="loot">
<b>
Loot: Colorful blade
<br>
slot: weapon
<br>
value: 7
</b>
<br />
<br />
<b>Current slot: weapon <br> Current weapon : Colorful blade <br> Current value: 7</b>
</div>
</div>
</body>
</html>

You need to link to the libary for the jQuery to work.
You can get it here https://code.jquery.com/
You were also correct with using the span around the word. Here is a working version
Loot: <span>Colorful</span> blade
Then target it to add the class
if ($('#loot:contains("Colorful")').length > 0) {
var str = document.getElementById("loot").innerHTML;
var res = str.replace("Colorful", "<span>Colorful</span>");
document.getElementById("loot").innerHTML = res;
$("#loot span").addClass("rainbow");
}
https://jsfiddle.net/o7phybe8/6/

Related

How to replace all blank space with &nbsp while ignoring html tags

I was replacing all of the spaces in a div element with so I could easily read all the spaces with a JavaScript file. When I was coding this I realized the elements inside the div would get messed up because properties like ids requires spaces between the tag name and the property would get replaced breaking the tag. How could I ignore the space in between the tag and the name and only replace the text spaces.
Code:
let el = document.getElementById('parent');
function replaceText() {
let text = el.innerHTML.split(' ').join(' ');
el.innerHTML = text;
console.log(text);
}
//I dont want the span tag or em tag to get messed up by this
<!DOCTYPE html>
<html>
<body>
<div id='parent'>
Lorem ipsum
<span id='element'>
<em id='child'>dolor sit amet</em>
</span>
</div>
<button onclick='replaceText()'>Change with nbsp</button>
</body>
</html>
The best way that I can think of is to look for text nodes in the element. You'll need to call the function recursively until there are no more text nodes. Here is some example code to get you started.
function replaceText(element) {
for (let childNode of element.childNodes) {
if (childNode.nodeType === Node.TEXT_NODE) {
childNode.data = ' ' + childNode.data.trim().replace(/ /g, '\u00a0') + ' '
continue
}
// Recursively replace text for child node
replaceText(childNode)
}
}
<!DOCTYPE html>
<html>
<body>
<div id='parent'>
Lorem ipsum
<span id='element'>
<em id='child'>dolor sit amet</em>
</span>
</div>
<button onclick='replaceText(document.getElementById("parent"))'>Change with nbsp</button>
</body>
</html>

jquery : how to toggle div after using search function on it?

I'm using a search function to highlight text (function 2) in different chapters. In parallel most of this text is stored in div called content to ease reading. You can toggle these div to read the text (function 1).
When text is found by function 2, it's no longer possible to toggle the text in this chapter. I suppose this is related to use of "this" in function 1 (If I delete this it works) or handlers (if I add live in front of click in function 1 it works but live is deprecated and remplacement "on" is not working).
// function 1 : toggle content when clicking the button
$(".chapter button").on('click',function(f) { //live deprecated to be replaced
f.preventDefault();
var id = $(this).attr('id');
console.log(id)
$('#' + id + '+*').toggle();
// toggle is not working when highlight function located in item in this specific chapter
});
// function 2 : highlight content
$('#monForm').submit(function(e) {
e.preventDefault();
console.log('submitted')
// clear form
var str = $('#valeurForm').val();
$('#valeurForm').val("");
console.log(str);
// highlight
var strCut = str.split(' ');
for (i = 0; i < strCut.length; i++) {
// grey chapter where the word is located
$("div[class='chapter']:contains(" + strCut[i] + ")").css("color", "#929aab");
// and highlight in red specific word
// but i want to highlight all occurences of the word in this chapter ? how can I define index d ?
$("div[class='chapter']:contains(" + strCut[i] + ")").each(function(d) {
$(this).html($(this).html().replace(strCut[i], '<font color="red">$&</font>'));
});
};
});
<head>
<meta charset="utf-8">
<style>
.content {
display: none;
}
</style>
</head>
<body>
<form name="search" id="monForm">
<input type="text" id="valeurForm">
</form>
<div class="chapter">
chapter 1
<button type="button" id="chapter1">Display content</button>
<div class="content">
content chapter1
</div>
</div>
<br>
<div class="chapter">
chapter 2
<button type="button" id="chapter2">Display content</button>
<div class="content">
content chapter2
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<!-- jQuery est inclus ! -->
</body>
The problem was your $(this).html(). The .replace that you did removes the event listener of your button, because it modifies the DOM. Instead of getting the whole .html(), I did it with .children(), and then replaced just the text of it.
About replacing all the occurrences of the chapter word, you could use a Regular Expression. Using a string will replace just the first occurrence of the string. With the regular expression you can replace all of them.
// function 1 : toggle content when clicking the button
$(".chapter button").click(function(f) { //live deprecated to be replaced
f.preventDefault();
var id = $(this).attr('id');
$('#' + id + '+*').closest('.content').toggle();
// toggle is not working when highlight function located in item in this specific chapter
});
// function 2 : highlight content
$('#monForm').submit(function(e) {
e.preventDefault();
console.log('submitted')
// clear form
var str = $('#valeurForm').val();
$('#valeurForm').val("");
// highlight
var strCut = str.split(' ');
for (i = 0; i < strCut.length; i++) {
// grey chapter where the word is located
$("div[class='chapter']:contains(" + strCut[i] + ")").css("color", "#929aab");
// and highlight in red specific word
$("div[class='chapter']:contains(" + strCut[i] + ")").each(function(d) {
var regex = new RegExp(strCut[i],"g")
$(this).children().each(function (index,element) {
const text = $(element).html().replace(regex,'<font color="red">$&</font>')
$(element).html(text)
})
});
};
});
<head>
<meta charset="utf-8">
<style>
.content {
display: none;
}
</style>
</head>
<body>
<form name="search" id="monForm">
<input type="text" id="valeurForm">
</form>
<div class="chapter">
chapter 1
<button type="button" id="chapter1">Display content</button>
<div class="content">
content chapter1 and the second ocurrence of chapter also highlighted
</div>
</div>
<br>
<div class="chapter">
chapter 2
<button type="button" id="chapter2">Display content</button>
<div class="content">
content chapter2
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<!-- jQuery est inclus ! -->
</body>
EDIT
I wasn't clear enough about the errors, sorry, and I've noticed the right solution.
The point is that, instead of modifying the parent element, I've changed the text of the childrens. When you change the whole html, you remove the listener of your buttons when you add it again to the html, and that's why isn't possible to toggle the divs.

How to inactivate parts of html code by Javascript

A JS newbie question:
I would like to inactivate a part of a html code (which I manually would do by <!-- ... -->) by Javascript, depending on a numeric variable (which I extract from the file name): If var > 10 do inactivate the code.
EDITED:
If possible only simple Javascript!
A demo html code:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<script>
var param = 10;
</script>
</head>
<body>
<p>Paragraph One</p>
<p>Beginning of the part to be removed if param > 10</p>
E-Mail<br><br>
This is simply something other.
Etc.
Etc.
<p>End of the part to be removed</p>
<p>Paragraph Ten</p>
</body>
</html>
Put everything you want to remove/hide inside one div with a specific class or id, then add an if condition and hide or remove the required div once the condition is true.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
</head>
<body>
<p>Paragraph One</p>
<div id="to_remove">
<p>Beginning of the part to be removed</p>
E-Mail<br><br>
This is simply something other.
Etc.
Etc.
<p>End of the part to be removed</p>
</div>
<p>Paragraph Ten</p>
<script type="text/javascript">
var param = 11;
if(param >10) document.getElementById("to_remove").remove();
//OR if you want to show the div later use this:
//if(param>10) document.getElementById("to_remove").style.display = 'none';
</script>
</body>
</html>
You can remove the elements from the DOM, e.g. by using removeChild():
document.getElementById('div').removeChild(document.getElementById('p2'));
<div id="div">
<p id="p1">Paragraph one</p>
<p id="p2">Paragraph two</p>
</div>
You can use css property for the same, add two classes active and inactive with css .active{display:block} and .inactive{display:none}.now you can use jquery to add and remove active and inactive classes according to your condition.like in jquery you can write
if(var > 10){
$("div").addClass('inactive');
}else{
$("div").removeClass('inactive');
}
A CSS + jQuery way of achieving this could be by adding the class disabled:
if(condition) {
var element = document.getElementByID('#sample_ID');
element.addClass("disabled");
}
This is assuming that you contain the code to be disabled in the <div id="sample_ID">
If you just want to hide it, you can do this by using CSS.
E.g. to hide <div id="myDiv">Bla</div> you'd use this:
var element = document.getElementById("myDiv");
element.style.display = "none";
And if you want to show it again at some point:
element.style.display = "block";
Live example:
function hideDiv() {
var element = document.getElementById("myDiv");
element.style.display = "none";
}
function showDiv() {
var element = document.getElementById("myDiv");
element.style.display = "block";
}
#myDiv {
border: solid 1px green
}
<button onclick="hideDiv()">Hide</button>
<button onclick="showDiv()">Show</button>
<br/>
<div id="myDiv">Bla</div>

Move element created to textarea

I would like to link the 2 scripts to send the result of the first to the clipboard, using the second script. Both work but separately
Thank you, sorry if I am not clear.
<html>
<body>
<p>Click the button to create a h1 element with some text.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var h = document.createElement("H1");
var t = document.createTextNode("It works");
h.appendChild(t);
document.body.appendChild(h);
}
</script>
<script type="text/javascript" src="ZeroClipboard.js">
</script>
<textarea name="box-content" id="box-content" rows="10" cols="70">
Will be copied to clipboard.
Line2.
Line3.
</textarea>
<br /><br />
Simply by changing .value of textarea:
document.getElementById('box-content').value = "It works";
You can not place a tag in textArea tag.
The <textarea> tag defines a multi-line text input control.A text area can hold an unlimited number of characters, and the text renders in a fixed-width font (usually Courier).The size of a text area can be specified by the cols and rows attributes, or even better; through CSS' height and width properties.
HTML textarea
Instead you can place text only in areatag.
function myFunction() {
//var h = document.createElement("H1");
var t = document.createTextNode("It works");
//h.appendChild(t);
document.getElementById('box-content').appendChild(t);
}
myFunction();
<textarea name="box-content" id="box-content" rows="10" cols="70"></textarea>

Citing a text area?

I'm just getting started in programming and somehow can't come up with any sensible approach to the following problem, so any help would be greatly appreciated! I have a .html file structured like this:
<head>
<title>ABC</title>
</head>
<body>
<div class="norm">
...
<span class="jnenbez">13</span>
....
<div class="Absatz">text</div>
<div class="Absatz">text</div>
<div class="Absatz">CITE HERE**</div>
The "norm" div is the one parent node. The "jnenbez" span and the "Absatz" divs are inside the "norm" div, but how deeply they are nested can vary. Now I want to cite the "CITE HERE" area, meaning to generate the output of "jnenbez 13 Absatz 3 ABC" - meaning getting the text content of the "jnenbez" span of the same "norm" div, getting the index number of the "Absatz" div, since it is the third child "Absatz" of the "norm" div and getting the content.
1) How could I give this string to the user, so he could copy paste it somewhere else? It seems it is not easily possible to modify the copy+paste behavior of Firefox. An obvious solution would be to put the output in brackets like [jnenbez...] at the end of each divs text content, but that would reduce readability of the html...
2) Is it even possible to automatically generate this output via JQuery?
Not sure about a good way to store/display the info.
Also, unsure of what other mark-up you would have in the class='norm' container. This is vitally important and impacts entirely the shape of the useful solution.
I've assumed a particular structure - one that says the first contained span is one of interest. Another assumption is that the only divs in the container are of interest and need to be counted.
I'm sure you can break it easily enough. :D
<!DOCTYPE html>
<html>
<head>
<script>
function onBtnPress(element)
{
var result;
var cont = element.parentNode;
var span = cont.getElementsByTagName('span')[0];
result = span.className + " ";
result += span.innerHTML + " ";
var divList = cont.getElementsByTagName('div');
result += divList[0].className + " ";
result += divList.length+" ";
result += document.title;
cont.getElementsByTagName('p')[0].innerHTML = result;
}
</script>
<title>ABC</title>
</head>
<body>
<div class="norm">
<span class="jnenbez">13</span>
<div class="Absatz">text</div>
<div class="Absatz">text</div>
<div class="Absatz">CITE HERE**</div>
<button onclick='onBtnPress(this);'>click me</button>
<p>[string here]</p>
</div>
<div class="norm">
<span class="Crapple">8</span>
<div class="ipod">worst</div>
<div class="ipod">music</div>
<div class="ipod">player</div>
<div class="ipod">I ever</div>
<div class="ipod">bought</div>
<div class="ipod">CITE HERE**</div>
<button onclick='onBtnPress(this);'>click me</button>
<p>[string here]</p>
</div>
</body>
</html>

Categories

Resources